社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用socket io和aiohttp在节点js和python之间进行数据传输

W. Churchill • 6 年前 • 988 次点击  

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

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

目前,我一直在学习这里的教程( https://tutorialedge.net/python/python-socket-io-tutorial/ )本教程使用socket io for JS和aiohttp for python。

我把HTML代码操纵成JS代码( 索引.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服务器( 服务器.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代码( 索引.js )最初是一个HTML脚本,它发送了一条消息,在__上单击一个按钮 http://localhost:8080 . 我将脚本调整为JS脚本,并添加了其他函数。因此,以下几行可能存在问题: 索引.js 在这里我设置socket io:

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

为了清楚起见,这里是原始的HTML代码( index.html文件 ) 索引.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转换相关的问题( Syntax error when trying to convert HTML file to JavaScript containing socket io, SyntaxError: Unexpected token < )

其次,因为本教程最初使用的是HTML文件而不是JS,所以我相信python脚本( 服务器.py )仍在等待HTML脚本的输出,因此我认为这些行在 服务器.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/ 或者我可能不确定我在找什么。

两个 服务器.py 索引.js 当前运行没有错误,但它们没有通信。

总之,JS文件( 索引.js )将数据发送到python服务器( 服务器.py )使用socket io,而使用aiohtp的python服务器将把分析的数据发送回同一个JS脚本。这将持续发生,直到手动停止其中一个脚本。

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38752
文章 [ 1 ]  |  最新文章 6 年前
xx NF xx
Reply   •   1 楼
xx NF xx    7 年前

我相信,在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 }