簡體   English   中英

Flask socket.IO 服務器上的 Node.js Socket.io 客戶端

[英]Node.js Socket.io client on Flask socket.IO server

我正在嘗試將 Node.js Socket.IO 客戶端連接到 Python/Flask Socket.IO 服務器。

在服務器(Raspberry Pi)上運行這個項目: Pi-GPIO-Server 這個項目已經有一個內置網站,它是一個 socket.io 客戶端,用於訪問 Raspberry Pi 的引腳。 整個項目運行良好。

現在我想從 Node.JS 客戶端訪問 socket.io 連接。

在服務器端,我已將服務器的 IP 和端口更新為:

if __name__ == '__main__':
    socketio.run(app, host="192.168.0.8", port=5000)

在客戶端,我的實現是(如項目文檔中所述)

var io = require('socket.io-client');
var socket = io.connect('http://192.168.0.8:5000', {path: '/', transports: ['websocket']});

socket.on( 'connect', (socket) => {
    console.log('Connected: ');
    console.log(socket);
});

socket.on( 'pins:list', (list) => {
    console.log('List of Pins: ');
    console.log(list);
});

任何想法,為什么我無法獲得連接? Flask 服務器中的客戶端是否有限制? 要發送什么特殊命令? 是否有可能調試連接?

@Christoph 請使用下面的代碼,你應該能夠連接......我有 Flash 服務器運行和 Nodejs 作為客戶端,它對我來說工作正常!!! 就我而言,我在同一台機器上同時運行服務器和客戶端,所以我使用localhost代替IP 地址

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from python flask srver");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect agan with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM