エンジニアリングとお金の話

都内で働くエンジニアの日記です。

【技術】pythonでwebsocketを試してみた

【SPONSORED LINK】

tornadoを使用してwebsocketを試してみた。

準備

pipにてtornadoとwebsocket-clientをインストール

サーバ側プログラム

#-*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
import tornado.websocket
 
cl=[]

#クライアントからメッセージを受けるとopen → on_message → on_closeが起動する
class WebSocketHandler(tornado.websocket.WebSocketHandler):

    #websocketオープン
    def open(self):
        print "open"
        if self not in cl:
            cl.append(self)
 
    #処理
    def on_message(self, message):
        print "on_message"
        for client in cl:
            print message
            #クライアントへメッセージを送信
            client.write_message(message + " webSocket")
 
    #websockeクローズ
    def on_close(self):
        print "close"
        if self in cl:
            cl.remove(self)

app = tornado.web.Application([
    (r"/websocket", WebSocketHandler)
])

if __name__ == "__main__":
   app.listen(8000)
   tornado.ioloop.IOLoop.instance().start()

クライアント側プログラム

#-*- coding:utf-8 -*-

from websocket import create_connection
import sys

#コネクションを張る
ws = create_connection("ws://localhost:8000/websocket")
 
#メッセージを送信
ws.send('hello world!')

#受信したメッセージを表示
print ws.recv()
 
#コネクションを切断
ws.close()

処理結果

f:id:hatakazu93:20161130134140p:plain

まとめ

tornadoを使用すればwebsocketが簡単に実装できる事が分かった。何かつくりたい。