简体   繁体   English

nodejs服务器,python客户端为什么他们不与websocket连接

[英]nodejs server, python client why are they not connecting with websocket

I'm trying to make a basic test of a nodejs server with a python client on Raspberry Pi.我正在尝试使用 Raspberry Pi 上的 python 客户端对 nodejs 服务器进行基本测试。 This has been much more difficult than I would have imagined to get right.这比我想象的要正确得多。 Very simple in the end.最后非常简单。

Here's the server:这是服务器:

const io = require('socket.io')(6079); listen on port 6079
var mysocket;

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

    socket.on('msg', (msg) => {
        console.log(msg);
        sendToClient("I got you python");
    });

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

function sendToClient(oTronic) {
  mysocket.emit('msg', oTronic); // <- wasn't 'msg' to start
}

Here's the python client which in the non-edited example didn't have a "message" event:这是 python 客户端,在未编辑的示例中没有“消息”事件:

import socketio

sio = socketio.Client()

@sio.event
def connect():
    print('Connection established with server to send message data.')
    send_msg("this is a test")

@sio.event
@sio.on('msg')
   def on_message(data):
   print("Python on_message received: " + data)

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

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

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

What have I missed??我错过了什么??

Ok, working now with a couple of minor edits.好的,现在进行一些小的编辑。 I didn't have the message, 'msg', correct in the send_msg function so I fixed that.我在 send_msg function 中没有正确的消息“msg”,所以我修复了它。

I also installed: pip install socketio-client but I don't know if that was necessary.我还安装了: pip install socketio-client 但我不知道这是否有必要。 Anyway, now it sends a message from python to nodejs and nodejs sends a message back to python.无论如何,现在它从 python 向 nodejs 发送一条消息,nodejs 向 python 发送一条消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM