简体   繁体   English

为什么我的异步 (NodeJS-Python) WebSocket 没有立即连接?

[英]Why is my asynchronous (NodeJS-Python) WebSocket not connecting immediately?

This is a continuation of a question I had earlier, Using Socket IO and aiohttp for data transfer between node JS and Python , based on this tutorial, https://tutorialedge.net/python/python-socket-io-tutorial/ .这是我之前提出的问题的延续,基于本教程https://tutorialedge.net/python/python-socket-io-tutorial/使用 Socket IO 和 aiohttp 在节点 JS 和 Python 之间进行数据传输

I have an asynchronous tunnel that connects a Node JS client ( send.js ) and a python server ( receive.py ).我有一个连接 Node JS 客户端( send.js )和 python 服务器( receive.py )的异步隧道。 Right now send.js outputs a random number and then sends it to the Python server ( receive.py ), which then sends the message back to the JS client.现在 send.js 输出一个随机数,然后将其发送到 Python 服务器( receive.py ),然后将消息发送回 JS 客户端。

The setup works, however, it takes a couple minutes for the server to start receiving data from send.js , and I do not know why.设置有效,但是,服务器需要几分钟才能开始从send.js接收数据,我不知道为什么。

The Node JS script will output data, but the server will not receive it for at least a couple minutes and even after it starts receiving data, it does not receive the data it did not get earlier, it will only receive the data from the moment the server and client can finally connect. Node JS 脚本会输出数据,但服务器至少在几分钟内不会收到它,即使在它开始接收数据之后,它也不会收到它之前没有收到的数据,它只会从那一刻开始接收数据服务器和客户端终于可以连接了。

I am not sure if this has something to with the Python side, Node JS side, or something else.我不确定这是否与 Python 方面、Node JS 方面或其他方面有关。

I am using Node 8.16.1 and Python 3.7.3我使用的是 Node 8.16.1 和 Python 3.7.3

The code is below:代码如下:

send.js发送.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();
});

receive.py接收.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)

Let me know if more information is needed.如果需要更多信息,请告诉我。

I don't know if you have to use the packages that you are using but here is my working version with ws package for node and asyncio and websockets packages for python.我不知道您是否必须使用您正在使用的包,但这是我的工作版本,其中包含用于 node 的ws包和用于 python 的asynciowebsockets包。 Have fun and nice question.有乐趣和好问题。

send.js发送.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)
})

receive.py接收.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM