简体   繁体   中英

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. 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:

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.

I also installed: pip install socketio-client but I don't know if that was necessary. Anyway, now it sends a message from python to nodejs and nodejs sends a message back to python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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