geventでWebSocketを使ってみる
WebSocketを使ってやりたいことがあったのですが
Pythonのモジュールを使いたかったので
Node.jsではなくPythonのgeventを使ってみました。
インストール
Pythonはインストール済みで
virtualenvで作った仮想環境で行います。
port install libevent # pip install geventだとエラーが出るのでソースからインストール curl http://pypi.python.org/packages/source/g/gevent/gevent-0.13.7.tar.gz#md5=c74004730c2543260b751b0aa782987c -o gevent-0.13.7.tgz tar xzf gevent-0.13.7.tgz cd gevent-0.13.7 python setup.py install -I /opt/local/include -L /opt/local/lib pip install gevent-websocket
コーディング
app.py
import sys from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler f = open("./index.html"); content = f.read() f.close() def app(environ, start_response): if environ["PATH_INFO"] == '/echo': ws = environ["wsgi.websocket"] while True: src = ws.receive() if src is None: break ws.send(src) else: start_response("200 OK", [ ("Content-Type", "text/html"), ("Content-Length", str(len(content))) ]) return iter([content]) if __name__=="__main__": server = pywsgi.WSGIServer(('127.0.0.1', 8000), app, handler_class=WebSocketHandler) server.serve_forever()
index.html
<html> <head> <title>gevent websocket test</title> </head> <body> <h1>test</h1> <div> <input name="send_input" id="send_input" /> <input type="button" value="push" onclick="send_data()" /> </div> <div> <textarea id="view"></textarea> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> var ws = new WebSocket("ws://127.0.0.1:8000/echo"); ws.onmessage = function(e) { $("#view").html($("#view").val() + e.data + "\n"); }; function send_data() { ws.send($("#send_input").val()); }; </script> </body> </html>
実行
python app.py
ブラウザで"http://127.0.0.1:8000/"にアクセスして
input textに文字を入力して"push"すると
textareaに入力した内容が表示されました!