リアルタイム通信がしたい
将来的にSNSを作りたいので、リアルタイム通信が必要になってくるので、基礎知識学習からスタート。
仕様
- Websocket
- flask
directory
- server.py
- templates/index.html
- server.py
# server.py from flask import Flask, request, render_template from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/hoge') def pipe(): if request.environ.get('wsgi.websocket'): ws = request.environ['wsgi.websocket'] while True: ws.send(input()) def main(): app.debug = True server = pywsgi.WSGIServer(("", 8080), app, handler_class=WebSocketHandler) server.serve_forever() if __name__ == "__main__": main()
- index.html
<!-- index.html --> <html> <head> <script type="text/javascript"> var ws = new WebSocket("ws://localhost:8080/hoge"); ws.onmessage = function(e) { document.getElementById("text-field").innerHTML = e.data; } </script> </head> <body> <h1>WebSocket test</h1> <p id="text-field"></p> </body> </html>
あとは、http://localhost:8080に繋げば終わり。