Node.js client for a socket.io server

前端 未结 5 1997
天涯浪人
天涯浪人 2020-11-28 20:22

I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.

But, I am wondering if it is possible, on another machine, to ru

5条回答
  •  一生所求
    2020-11-28 21:25

    Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

    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 the socket io server");
            });
        
            //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 again with server");
                }
                // else the socket will automatically try to reconnect
              });
        
            socket.on('error', (error) => {
                console.log(error);
            });
    

提交回复
热议问题