Python客户端和NodeJS服务器简单通信

时间:2020-08-24 23:09:39

标签: python node.js websocket socket.io

我有一个运行良好的NodeJS Electron应用程序。我有一个Python脚本,可以处理一些视频,还需要将一些短字符串发送到NodeJS才能在Electron应用程序上显示。我一直在尝试使WebSockets正常工作,并且Python节点通信似乎有很多问题(与Node-Node相比),所以我想知道以前是否有任何更简单的跨语言通信方法排除所有故障。

Stdout是不切实际的,因为Python脚本可能无法在Node上正常运行。 SocketIO似乎使用HTTP,这对于发送40字节的数据似乎有些过头。是否有一种超级简单的方法可以通过TCP发送几个字节?还是SocketIO会达到预期的效果?

感谢您的帮助!

我的解决方案

编辑:在进一步研究socket.io之后,它实际上总体上确实很简单!为了将来参考,这是我的NodeJS服务器代码:

const io = require('socket.io').listen(6079); // import socket.io module and listen on port 6079

io.on('connection', (socket) => {
    console.info('connection established');

    socket.on('msg', (msg) => {
        console.log(msg);
        // do something with the message
    });

    socket.on('disconnect', function() {
      console.log('client disconnected');
   });
});

这是Python客户端的代码:

import socketio
from time import sleep # just used for timing the messages

sio = socketio.Client()

@sio.event
def connect():
    print('Connection established with server to send message data.')

def send_msg(msg):
    print("sending")
    sio.emit('msg', msg)

@sio.event
def disconnect():
    print('Disconnected from websocket! Cannot send message data.')

sio.connect('ws://localhost:6079')

# list of messages to send
MESSAGE_LIST = ["66903222854465",
                "36558352171508",
                "42493680134299",
                "32010903761366",
                "37556732408598",
                "00418984412935",
                "54555467232969",
                "95461295964563",
                "63543734057786",
                "37925062203941"]

# logic to send the 10 messages then close connection
x = 0
while x < 10:
    send_msg(MESSAGE_LIST[x])
    sleep(1)
    x += 1

sio.disconnect()

我不确定为什么很难找到服务器/客户端代码的准系统实现(尤其是跨语言实现),但这似乎就是如此。希望这会有所帮助!

0 个答案:

没有答案