我的总体目标是在 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')
白衣非少年
相关分类