使用Socket IO和aiohttp在节点JS和Python之间进行数据传输

Using Socket IO and aiohttp for data transfer between node JS and Python

我的总体目标是在 JavaScript 文件(使用节点 运行)中生成随机数流,并以异步时间间隔将它们发送到 python 脚本.一旦数字在 python 中,脚本将确定数字是否为偶数。如果是,则将数字发送回 JavaScript 文件。我主要关注的是获取 JavaScript 和 Python 之间的通信。

一旦我启动 JavaScript 文件和 python 服务器,它们将继续 运行ning 直到我停止它们。

目前,我一直在研究位于此处 (https://tutorialedge.net/python/python-socket-io-tutorial/) 的教程。本教程对 JS 使用 socket io,对 python 使用 aiohttp。

我把html代码操作成JS代码(index.js),如下:

// index.js    
var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});

function generateNumber() {
   let n = Math.floor(Math.random() * 50);
   let json = {
       'number': n
   }
   console.log(json);
   return json;
}

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500;
    setTimeout(function() {
            generateNumber();
            loop();  
    }, rand);
}());

function sendMsg() {
  socket.emit("message", generateNumber());
}

socket.on("message", function(data) {
console.log(data);
});

我创建了一个函数 (generateNumber) 来生成以 JSON 格式输出的随机数。我正在使用 JSON,因为我相信当数字到达 python 脚本时,它将允许数据轻松转换为列表和整数。循环函数允许以随机间隔连续创建数字,取自此处:Randomize setInterval ( How to rewrite same random after random interval)

下面显示的 python 服务器 (server.py) 取自教程 (https://tutorialedge.net/python/python-socket-io-tutorial/):

# server.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)

# we can define aiohttp endpoints just as we normally
# would with no change
async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

# 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)

# We bind our aiohttp endpoint to our app
# router
app.router.add_get('/', index)

# We kick off our server
if __name__ == '__main__':
    web.run_app(app)

截至目前,当我运行 node index.js时,会以随机间隔连续生成随机数,并在终端中看到输出。但是我在服务器端没有得到响应。

我认为问题与以下两个问题有关:

首先,我当前的 JS 代码 (index.js) 最初是一个 html 脚本,它发送一条消息,点击托管在“http://localhost:8080。”我将脚本调整为JS脚本,并添加了额外的功能。因此,在 index.js 的以下几行中,我设置套接字 io:

可能存在问题
var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});

为了清楚起见,这里是原始的 html 代码 (index.html) index.js 基于:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <button onClick="sendMsg()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
      const socket = io("http://localhost:8080");

      function sendMsg() {
        socket.emit("message", "HELLO WORLD");
      }
    </script>
  </body>
</html>

我之前也问过一个与 html 到 JS 转换 ()

相关的问题

其次,由于教程最初使用的是html文件而不是JS,我认为python脚本(server.py)是仍在等待 html 脚本的输出,所以我认为 server.py 中的这些行需要更改:

async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

但我不确定如何进行适当的更改,我在 aiohttp 站点 (https://aiohttp.readthedocs.io/en/stable/) 上查找对我的问题的引用时遇到问题,或者我可能不确定我在寻找什么。

server.pyindex.js 目前 运行 没有错误,但它们不是沟通。

总的来说,JS 文件 (index.js) 将数据发送到 python 服务器 (server.py ) 使用套接字 io,而 python 服务器使用 aiohttp,将把分析后的数据发送回同一个 JS 脚本。这将持续发生,直到手动停止其中一个脚本。

如果有任何需要澄清的地方,请随时询问。

我认为,在 JS 部分,您应该在某处调用 sendMsg() 以发出消息。

已更新

const io = require('socket.io-client');

const socket = io('http://localhost:8080');

socket.on('message', data => {
  console.log('Got from server: ');
  console.log(data);
});

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;
  console.log(`Setting timeout ${rand}ms`);
  setTimeout(() => {
    sendMsg();
    loop();
  }, rand);
}

socket.on('connect', () => {
  console.log('Connected to server');
  loop();
});

我在两边都使用节点。服务器端只是发回每条收到的消息。 日志如下所示:

Connected to server
Setting timeout 1685ms
Sending to server:
{ number: 21 }
Setting timeout 1428ms
Got from server: 
{ number: 21 }
Sending to server:
{ number: 40 }
Setting timeout 2955ms
Got from server: 
{ number: 40 }