【发布时间】:2019-04-22 01:24:33
【问题描述】:
我的总体目标是在 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')
# 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时,随机数会以随机间隔连续生成,并且可以在终端中看到输出。但我在服务器端没有得到响应。
我认为该问题与以下 2 个问题有关:
首先,我当前的 JS 代码 (index.js) 最初是一个 html 脚本,它通过“http://localhost:8080”上的按钮单击发送消息。我将脚本调整为 JS 脚本,并添加了附加功能。因此,在我设置套接字 io 的 index.js 的以下行中可能存在问题:
var socket = require('socket.io-client')('http://localhost:8080');
socket.on('connect', function(){});
为清楚起见,以下是 index.js 所基于的原始 html 代码 (index.html):
<!-- 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脚本(server.py)仍在等待html脚本的输出,所以我认为这些行在server.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/) 上查找对我的问题的引用时遇到问题,或者我可能不确定我在寻找什么。
server.py 和 index.js 目前都可以正常运行,但它们没有通信。
总体而言,JS 文件 (index.js) 将使用 socket io 将数据发送到 python 服务器 (server.py),而 python 服务器使用aiohttp,会将分析后的数据发送回相同的 JS 脚本。这将持续发生,直到手动停止其中一个脚本。
如果需要任何澄清,请随时询问。
【问题讨论】:
标签: javascript python node.js http aiohttp