2023年8月20日日曜日

FlaskでSocket.IOでなくWebSocketを使うには

 ソースだけです


サーバー側

from flask import Flask

from flask_sockets import Sockets

from flask import render_template


from gevent import pywsgi

from geventwebsocket.handler import WebSocketHandler

from werkzeug.routing import Rule



app = Flask(__name__)

sockets = Sockets(app)



# @sockets.route('/c2', websocket= True )

def echo_socket(ws):


    #breakpoint()

    print("kimasita")

    while not ws.closed:

        message = ws.receive()

        if message != None:

            ws.send(message)



sockets.url_map.add(Rule('/c2', endpoint=echo_socket, websocket=True))




@app.route('/')

def hello():

    #return 'Hello World!'

    return render_template("index.html")



if __name__ == "__main__":

    server = pywsgi.WSGIServer(('', 8001), app, handler_class=WebSocketHandler)

    server.serve_forever()


ブラウザ側

<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://ik1-446-55369.vs.sakura.ne.jp:8001/c2");

ws.onmessage = function(e) {

  $("#view").html($("#view").val() + e.data + "\n");

};

function send_data() {

  //ws.send( "abcdefg");

        ws.send($("#send_input").val());

};

</script>

</body>

</html>