【问题标题】:nodejs server, python client why are they not connecting with websocketnodejs服务器,python客户端为什么他们不与websocket连接
【发布时间】:2021-02-23 14:18:59
【问题描述】:

我正在尝试使用 Raspberry Pi 上的 python 客户端对 nodejs 服务器进行基本测试。这比我想象的要正确得多。最后很简单。

这是服务器:

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
}

这是未编辑示例中没有“消息”事件的 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')

我错过了什么??

【问题讨论】:

    标签: python node.js socket.io raspberry-pi


    【解决方案1】:

    好的,现在进行一些小的修改。我在 send_msg 函数中没有正确的消息“msg”,所以我修复了它。

    我也安装了: pip install socketio-client 但我不知道这是否有必要。无论如何,现在它从 python 向 nodejs 发送一条消息,nodejs 向 python 发送一条消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 2013-12-04
      • 1970-01-01
      相关资源
      最近更新 更多