我的总体目标是在一个javascript文件(使用node运行)中生成一个随机数流,并以异步时间间隔将它们发送到一个python脚本。一旦数字在python中,脚本将确定数字是否是偶数。如果是,这些数字将被发送回javascript文件。我的主要工作是获取JavaScript和Python之间的通信。
一旦我启动了javascript文件和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)
# 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脚本,它发送了一条消息,在__上单击一个按钮
索引.js
在这里我设置socket io:
var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});
为了清楚起见,这里是原始的HTML代码(
index.html文件
)
索引.js
基于:
DocumentHit Me
const socket = io("http://localhost:8080");
function sendMsg() {
socket.emit("message", "HELLO WORLD");
}
其次,因为本教程最初使用的是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脚本。这将持续发生,直到手动停止其中一个脚本。
如果需要任何澄清,请随时询问。