简体   繁体   English

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

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

My overall goal is to generate a stream of random numbers in a JavaScript file (which is run using node) and send them to a python script in asynchronous time intervals. 我的总体目标是在JavaScript文件(使用node运行)中生成随机数流,并在异步时间间隔内将其发送到python脚本。 Once the numbers are in python, the script will determine if the numbers are even, or not. 一旦数字在python中,脚本将确定数字是否为偶数。 If they are, the numbers are sent back to the JavaScript file. 如果是,则将这些数字发送回JavaScript文件。 My main focus is to get the communication between JavaScript and Python. 我的主要重点是获取JavaScript和Python之间的通信。

Once I begin the JavaScript file and python server, they will continue running until I stop them. 一旦启动JavaScript文件和python服务器,它们将继续运行,直到我停止它们为止。

Currently, I have been working off the tutorial located here ( https://tutorialedge.net/python/python-socket-io-tutorial/ ). 目前,我正在研究位于此处的教程( https://tutorialedge.net/python/python-socket-io-tutorial/ )。 The tutorial uses socket io for JS and aiohttp for python. 本教程将Socket io用于JS,将aiohttp用于python。

I manipulated the html code into a JS code ( index.js ), which is below: 我将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);
});

I created a function (generateNumber) to produce random numbers outputted in JSON format. 我创建了一个函数(generateNumber)以产生以JSON格式输出的随机数。 I am using JSON because I believe it will allow for data to be easily converted into lists and integers when the numbers reach the python script. 我使用JSON是因为我相信当数字到达python脚本时,它将允许将数据轻松转换为列表和整数。 The loop function allows the numbers to be created at random intervals continuously and was taken from here: Randomize setInterval ( How to rewrite same random after random interval) 循环功能允许以随机间隔连续创建数字,并从此处获取: Randomize setInterval(如何在随机间隔后重写相同的随机数)

The python server ( server.py ) shown below, was taken from the tutorial ( https://tutorialedge.net/python/python-socket-io-tutorial/ ): 下面显示的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)

As of now, when I run node index.js , random numbers are continuously generated at random intervals and the output can be seen in the terminal. 到目前为止,当我运行node index.js ,随机数会以随机间隔连续生成,并且可以在终端中看到输出。 But I am not getting a response on the server side. 但是我没有在服务器端得到响应。

I believe the problem is related to the following 2 issues: 我认为该问题与以下两个问题有关:

First, my current JS code ( index.js ) was originally a html script that sent a message with a button click hosted on “ http://localhost:8080 .” I adjusted the script to be a JS script, as well as adding additional functions. 首先,我当前的JS代码( index.js )最初是一个HTML脚本,该脚本通过单击位于“ http:// localhost:8080 ”上的按钮来发送消息。我将该脚本调整为JS脚本,并添加了附加功能。 So there may be an issue in the following lines of index.js where I setup socket io: 因此,在我设置套接字io的以下index.js行中可能存在问题:

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

For clarity, here is the original html code ( index.html ) that index.js is based off: 为了清楚起见,这是index.js基于的原始html代码( index.html ):

<!-- 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>

I also asked a previous question related to the html to JS conversion ( Syntax error when trying to convert HTML file to JavaScript containing socket io, SyntaxError: Unexpected token < ) 我还问了与html到JS转换相关的先前问题( 尝试将HTML文件转换为包含套接字io的JavaScript时出现语法错误,SyntaxError:意外令牌<

Second, because the tutorial originally used a html file rather than JS, I believe the python script ( server.py ) is still waiting on output from a html script, so I think these lines in server.py need to be changed: 其次,由于本教程最初使用的是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')

But I am unsure how to make the proper changes, I am having issues finding references to my question on the aiohttp site ( https://aiohttp.readthedocs.io/en/stable/ ), or I may be unsure as to what I am looking for. 但是我不确定如何进行适当的更改,我在aiohttp网站( https://aiohttp.readthedocs.io/en/stable/ )上找不到对我的问题的引用时遇到问题,或者我可能不确定我该做什么正在寻找。

Both server.py and index.js currently run without errors, but they are not communicating. 目前server.pyindex.js都没有错误运行,但是它们没有通信。

Overall, the JS file ( index.js ) will be sending data to a python server ( server.py ) using socket io, and the python server, using aiohttp, will be sending back the analyzed data to the same JS script. 总体而言,JS文件( index.js )将使用套接字io将数据发送到python服务器( server.py ),而python服务器将使用aiohttp将数据发送回相同的JS脚本。 This will happen continuously until one of the scripts is stopped manually. 这将连续发生,直到手动停止其中一个脚本为止。

If any clarification is needed on anything, please feel free to ask. 如果需要任何澄清,请随时提出。

I believe, in JS part, you should call sendMsg() somewhere in order to emit a message. 我相信,在JS部分,您应该在某处调用sendMsg()以便发出消息。

Updated 更新

 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(); }); 

I was using node on both sides. 我在两侧都使用节点。 The server side just sends back every received message. 服务器端只是发回每个收到的消息。 The logs look like this: 日志如下所示:

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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