[英]Why is my asynchronous (NodeJS-Python) WebSocket not connecting immediately?
这是我之前提出的问题的延续,基于本教程https://tutorialedge.net/python/python-socket-io-tutorial/ , 使用 Socket IO 和 aiohttp 在节点 JS 和 Python 之间进行数据传输。
我有一个连接 Node JS 客户端( send.js )和 python 服务器( receive.py )的异步隧道。 现在 send.js 输出一个随机数,然后将其发送到 Python 服务器( receive.py ),然后将消息发送回 JS 客户端。
设置有效,但是,服务器需要几分钟才能开始从send.js接收数据,我不知道为什么。
Node JS 脚本会输出数据,但服务器至少在几分钟内不会收到它,即使在它开始接收数据之后,它也不会收到它之前没有收到的数据,它只会从那一刻开始接收数据服务器和客户端终于可以连接了。
我不确定这是否与 Python 方面、Node JS 方面或其他方面有关。
我使用的是 Node 8.16.1 和 Python 3.7.3
代码如下:
发送.js
const io = require('socket.io-client');
const socket = io('http://localhost:8080');
socket.on('reply', message => {
console.log('Got from server: ');
console.log(message);
});
function generateNumber() {
const n = Math.floor(Math.random() * 50);
return { number: n };
}
function sendMsg() {
const json = generateNumber();
console.log('Sending to server:');
console.log(json);
socket.emit('message', json);
}
function loop() {
const rand = Math.round(Math.random() * (3000 - 500)) + 500;
setTimeout(() => {
sendMsg();
loop();
}, rand);
}
socket.on('connect', () => {
console.log('Connected to server');
loop();
});
接收.py
from aiohttp import web
import socketio
# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)
# If we wanted to create a new websocket endpoint,
# use this decorator, passing in the name of the
# event we wish to listen out for
@sio.on('message')
async def print_message(sid, message):
# When we receive a new event of type
# 'message' through a socket.io connection
# we print the socket ID and the message
#print("Socket ID: " , sid)
print(message)
await sio.emit('reply', message)
# We kick off our server
if __name__ == '__main__':
web.run_app(app)
如果需要更多信息,请告诉我。
我不知道您是否必须使用您正在使用的包,但这是我的工作版本,其中包含用于 node 的ws
包和用于 python 的asyncio
和websockets
包。 有乐趣和好问题。
发送.js
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:8080')
console.log(ws)
function generateNumber() {
const n = Math.floor(Math.random() * 50);
return {
number: n
};
}
function sendMsg() {
const json = JSON.stringify(generateNumber());
console.log('Sending to server:');
console.log(json);
ws.send(json);
}
function loop() {
setTimeout(() => {
sendMsg();
loop();
}, 5000);
}
ws.on('open', function open() {
console.log('connect')
console.log(ws)
loop()
})
ws.on('message', function(data) {
console.log(data)
})
接收.py
import asyncio
import websockets
async def start(websocket, path):
print("connected")
while True:
data = await websocket.recv()
print(f"< {data}")
await websocket.send(data)
async def main():
server = await websockets.serve(start, 'localhost', 8080)
await server.wait_closed()
asyncio.run(main())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.