这是我到目前为止开发的。首先,我的 websocket 服务器:
// app.js
const spawn = require('child_process');
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8080 })
wss.on('connection',ws => {
ws.on('message', message => {
const python = spawn('python', ['-u', 'main.py', message])
python.stdout.on('data', function (data) {
// Pipe data from python script ...
dataToSend = data.toString('utf8');
ws.send(dataToSend)
});
python.on('error', err => {
console.log(err)
})
})
ws.on('close', () => {
console.log('Client has disconected')
})
}).on('error', err => {
console.log(err)
})
它的基础知识用于child_process生成一个传递message从客户端发送的 python 脚本。 -u传递是为了刷新 python 脚本打印,因此它可以流出python.stdout并发送到客户端。
这是从 app.js websocket 服务器调用的我的 python 脚本:
# main.py
import time, sys
i = int(sys.argv[1])
while i > 0:
print(i)
i-=1
time.sleep(1)
# this while is just anexemple of some pre-script process
# (for exemple, signin on user account)
# after signin...
print('input something from client: ')
x = input()
while True:
print(x)
time.sleep(1)
# use input x variable
# here is where my code happens and the program keeps executing
pass
如您所见,我正在使用从服务器message传递过来的信息spawn()来保持我的第一个while存活。这只是一个例子,我需要用户提供这种输入。
保持你的注意力,x = input()因为这是我的主要问题
最后,我的客户端 websocket
// client.js
const WebSocket = require('ws');
let socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(e) {
let someClientInfo = 2
console.log("sending data...");
socket.send(someClientInfo);
};
当然,当客户端收到最后一行时,它会一直卡住,因为他无法从他这边输入任何内容。他刚刚收到来自 python 的输出流。
有人知道是否可以将第二个输入传递给我正在运行的 python 脚本吗?我开始认为这也许是不可能的,但我不能考虑另一种方法来做到这一点。如果是child_process做不到的事情,我应该寻找什么方法?
我的主要目的是与服务器上运行的 python 脚本保持有效通信,以便我可以将此输入从客户端传递给 python。
我希望能够断开与该套接字的连接,然后再次连接并继续接收 python 脚本输出。到目前为止,我也找不到办法做到这一点。
我的主脚本不能在服务器代码中(也许如果你对 flask 的基本实现或类似的东西感到困惑),因为我希望能够启动多个脚本并且每个客户端用户都应该能够与他自己的 python 脚本在服务器上运行。每个用户都会有自己的main.py
到目前为止,我还没有考虑如何让所有这些进程在服务器上运行,或者即使这样做是安全的。对此的任何建议都将非常感激,我也将非常感激。
沧海一幻觉
相关分类