使用Socket IO和aiohttp在节点JS和Python之间进行数据传输 [英] Using Socket IO and aiohttp for data transfer between node JS and Python

查看:71
本文介绍了使用Socket IO和aiohttp在节点JS和Python之间进行数据传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的总体目标是在JavaScript文件(使用node运行)中生成随机数流,并在异步时间间隔内将其发送到python脚本.一旦数字在python中,脚本将确定数字是否为偶数.如果是,则将这些数字发送回JavaScript文件.我的主要重点是获取JavaScript和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. Once the numbers are in python, the script will determine if the numbers are even, or not. If they are, the numbers are sent back to the JavaScript file. 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.

当前,我正在研究位于此处的教程( https://tutorialedge.net/python/python-socket-io-tutorial/).本教程将Socket io用于JS,将aiohttp用于python.

Currently, I have been working off the tutorial located here (https://tutorialedge.net/python/python-socket-io-tutorial/). The tutorial uses socket io for JS and aiohttp for python.

我将html代码处理为下面的JS代码( index.js ):

I manipulated the html code into a JS code (index.js), which is below:

// 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脚本时,它将允许将数据轻松转换为列表和整数.循环功能允许以随机间隔连续创建数字,并从此处获取:

I created a function (generateNumber) to produce random numbers outputted in JSON format. 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. 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)

下面显示的python服务器( server.py )是从教程(

The python server (server.py) shown below, was taken from the tutorial (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 时,将以随机间隔连续生成随机数,并且可以在终端中看到输出.但是我没有在服务器端得到响应.

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. But I am not getting a response on the server side.

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

I believe the problem is related to the following 2 issues:

首先,我当前的JS代码( index.js )最初是一个HTML脚本,该脚本通过单击" index.js 的以下几行中可能存在问题:

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. So there may be an issue in the following lines of index.js where I setup socket io:

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

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

For clarity, here is the original html code (index.html) that index.js is based off:

<!-- 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转换有关的先前问题(

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,所以我认为python脚本( server.py )仍在等待html脚本的输出,因此我认为这些行 server.py 需要更改:

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:

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

但是我不确定如何进行适当的更改,我在aiohttp网站上找到对我的问题的参考时遇到问题(

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.

server.py index.js 当前都没有错误运行,但是它们没有通信.

Both server.py and index.js currently run without errors, but they are not communicating.

总体而言,JS文件( index.js )将使用套接字io将数据发送到python服务器( server.py ),而python服务器将使用aiohttp,将把分析后的数据发送回相同的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. This will happen continuously until one of the scripts is stopped manually.

如果需要任何澄清,请随时询问.

If any clarification is needed on anything, please feel free to ask.

推荐答案

我相信,在JS部分,您应该在某个地方调用sendMsg()以便发出消息.

I believe, in JS part, you should call sendMsg() somewhere in order to emit a message.

已更新

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 }

这篇关于使用Socket IO和aiohttp在节点JS和Python之间进行数据传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆