我正在尝试打开从node.js服务器到python文件的Web套接字连接,以实现进程间通信。以下代码运行但python只是挂起,而不是不断打印" test"就像我期望的那样。
connect
代码已从此来源修改:Socket.IO Client Library in Python
python_ws.py
import websocket, http.client
class Socket(object):
def __init__(self, store):
self.store = store
def connect(self, port):
port = str(port)
conn = http.client.HTTPConnection('localhost:' + port)
conn.request('POST','/socket.io/1/')
resp = conn.getresponse()
print("RESP")
print(resp.read())
print("/RESP")
hskey = str(resp.read().split(b':')[0])
self.ws = websocket.WebSocket(
'ws://localhost:' + port + '/socket.io/1/websocket/' + hskey,
on_open = self.on_open,
on_message = self.on_message,
on_close = self.on_close)
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("websocket.py: Connection closed")
def on_open(ws):
print("websocket.py: Connection opened")
store = 10
port = 3010
ws = Socket(store)
ws.connect(port)
socketio.js
var port = 3010;
var io = require('socket.io')(port);
io.on('connection', function (socket) {
console.log('socketio.js: Connected');
io.emit('this', { will: 'be received by everyone'});
socket.on('disconnect', function () {
console.log('socketio.js: Disconnected');
});
socket.on('test', function (data) {
console.log(data);
});
});
while (true) {
io.emit("message", {test: "test"});
}