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

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


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


目前,我一直在学习位于此处(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')



蝴蝶不菲
浏览 227回答 1
1回答

白衣非少年

我相信,在 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 serverSetting timeout 1685msSending to server:{ number: 21 }Setting timeout 1428msGot from server: { number: 21 }Sending to server:{ number: 40 }Setting timeout 2955msGot from server: { number: 40 }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python