Back to tech

pythonでwebソケット通信する(サーバー)

1 min read
Table of Contents

以前にESP8266におけるWebソケット通信について記載しました。 ここ

ESP8266間だけでなく、他のコンピュータとでも接続できなかなぁと考えていました。

ついでに「Pythonで実装できたら!」と思い色々と調べてみると簡単にソケットサーバーを構築でき、操作できるライブラリを見つけました。

メモがてら残しておきます

使用したライブラリは”simple-websocket-server”というものです

GitHub - dpallot/simple-websocket-server: A python based websocket server that is simple and easy to use.
github.com
image

他にもtornadoというモジュールがありましたが、使いやすさや学習しやすさを考えてると上記のものが楽そうです。

インストール

pip install git+http://github.com/dpallot/simple-websocket-server.git

使い方

基本Githubと似ていますが・・・

Port:8000

# -*- coding:utf-8 -*-
#!/usr/bin/env python

from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

class SimpleEcho(WebSocket):

    def handleMessage(self):
        # echo message back to client
        print(self.data)
        
        # unicodeで送信しないとエラーがでる
        self.sendMessage(u"ok")


    def handleConnected(self):
        print(self.address, 'connected')

    def handleClose(self):
        print(self.address, 'closed')

server = SimpleWebSocketServer('', 8000, SimpleEcho)
server.serveforever()

selfを配列でためておきながら通信をすると、「もしクライアント1からデータが来たら、クライアント2へ信号を送る」等ができるます。

とても便利なモジュールです。

参考文献

・GitHub http://github.com/dpallot/simple-websocket-server