WebSocketでデータの受け渡しをするときの例のプログラムです。
pip install websocket-server
サーバー側です。
python
1from websocket_server import WebsocketServer
2
3def new_client(client, server):
4 print ("new_client:", client['address'])
5
6def message_received(client, server, message):
7 print ("message_received:", message)
8 server.send_message(client, "hello from server")
9
10server = WebsocketServer(port=5001, host='127.0.0.1')
11server.set_fn_new_client(new_client)
12server.set_fn_message_received(message_received)
13server.run_forever()
クライアント側です。
<body>
<div id="debug">debug</div>
<script>
var sock = new WebSocket('ws://127.0.0.1:5001');
sock.addEventListener('open',function(e){
console.log('socket open');
sock.send('hello from client');
});
sock.addEventListener('message',function(e){
debug.textContent = e.data;
});
</script>
</body>