[英]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.