我正在尝试在Python中设置socket.io服务器和在JavaScript中设置socket.io客户端。
我找到了与客户端服务器进行对话的JS客户端和与python服务器进行对话的python客户端的示例-但与python服务器进行对话的JS客户端没有示例。因此,我试图结合来自不同示例的代码。>
客户端(由apache提供的html文件,托管在您想要的任何位置)
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script>
socket = io.connect('http://localhost:5000');
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
socket.on('msg',function(data) {
console.log('Received a message from the server!',data);
});
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function send(message) {
socket.send('msg',message);
};
</script>
服务器:
import eventlet
import socketio
sio = socketio.Server()
# the index.html file hosted by eventlet is a dummy file
# it appears to be required to host some html file..
app = socketio.WSGIApp(sio, static_files={
'/': {'content_type': 'text/html', 'filename': 'index.html'}
})
@sio.on('connect')
def connect(sid, environ):
print('connect ', sid)
@sio.on('msg')
def message(sid, data):
print('message ', data)
@sio.on('disconnect')
def disconnect(sid):
print('disconnect ', sid)
if __name__ == '__main__':
eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
运行此设置时,我可以在Python终端中看到客户端如何尝试连接:
disconnect db71fa07154c45d4b6e6c80073d27e17
127.0.0.1 - - [03/Feb/2019 17:28:04] "POST /socket.io/?EIO=3&transport=polling&t=MYqC39S&sid=4e1045977dd14223b0d2913752dd5cf1 HTTP/1.1" 400 233 0.000296
127.0.0.1 - - [03/Feb/2019 17:28:04] "POST /socket.io/?EIO=3&transport=polling&t=MYqC39Z&sid=4e1045977dd14223b0d2913752dd5cf1 HTTP/1.1" 400 233 0.000201
connect 8650c5c7f735492e84a6e8774a20b069
127.0.0.1 - - [03/Feb/2019 17:28:05] "GET /socket.io/?EIO=3&transport=polling&t=MYqC3Q3 HTTP/1.1" 200 396 0.001240
disconnect 8650c5c7f735492e84a6e8774a20b069
127.0.0.1 - - [03/Feb/2019 17:29:05] "GET /socket.io/?EIO=3&transport=polling&t=MYqC3QC&sid=8650c5c7f735492e84a6e8774a20b069 HTTP/1.1" 400 233 60.005087
(12281) accepted ('127.0.0.1', 46478)
127.0.0.1 - - [03/Feb/2019 17:29:23] "GET /socket.io/?
在chrome中,我看到了客户端连接尝试:
index.js:83 POST http://localhost:5000/socket.io/?EIO=3&transport=polling&t=MYqDzXq&sid=d08f2f55533b43ea81bd2f98201de277 400 (BAD REQUEST)
i.create @ index
index.js:83 POST http://localhost:5000/socket.io/?EIO=3&transport=polling&t=MYqDzXz&sid=d08f2f55533b43ea81bd2f98201de277 400 (BAD REQUEST)
i.create @ index.
index.js:83 WebSocket connection to 'ws://localhost:5000/socket.io/?EIO=3&transport=websocket&sid=f23be764110d44cda684e633a990e0d7' failed: Error during WebSocket handshake: Unexpected response code: 400
他们似乎在交流-但出了点问题,因此连接从未完全建立。
答案 0 :(得分:0)
发现了问题-我有两个正在运行的服务器实例。其中一台被作为后台线程触发并一直保持运行状态,所以我忘记了它……在同一端口上监听了两台服务器,这就是通信混乱的原因。
现在一切正常,因此该代码可用作python-JS socket.io通信的最小工作示例。
答案 1 :(得分:0)
要从JS客户端脚本向服务器发送消息,必须使用“发射”而不是“发送”。
// Sends a message to the server via sockets
function send(message) {
socket.emit('msg',message);
};