Ad

Why Socket.io Doesnt Emit In A Real Live Server?

- 1 answer

I have a simple chat application, with react-native, nodejs, socket.io and express.

this app is working fine on my laptop as I am using local nodejs server with epxress

Now I am using real live server from hostwinds Here I have setuped nodejs+express server. Here the connection works well, but problem is it doesnt emit from client or from server, I mean First time it connects to server successfully, but doesnt emit event or send data.

My client code is:

import io from 'socket.io-client';

class InitSocket extends Component{
  constructor(props){
        super(props);
        this.socket = io('http://LiveServerIP:3000/', { transports: ['websocket'] });
        this.socket.emit('onsenddata', 'Hello from client to server');
  }
}

The above code emit('onsenddata', 'some data'); just works some times, but most of the time does not works. Here in above code as you can see I am using the hostwinds live server ip address.

following code works very well, while is the same as above code, just it is in my laptop and ip address is localhost:

import io from 'socket.io-client';

class InitSocket extends Component{
  constructor(props){
        super(props);
        this.socket = io('http://localhost:3000/', { transports: ['websocket'] });
        this.socket.emit('onsenddata', 'Hello from client to server');
  }
}

My server code is:

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
io.on('connection', cs => {

  cs.on('onsenddata', username => {
       cs.broadcast.to(cs.id).emit('onsenddata', 'Hello from server to client');
  });

});

server.listen(port, err => {
    if(err){
        console.error("Some Error: "+err);
    }else{
        console.log(`Server is running on port: ${port}`);
    }
});
Ad

Answer

Problem was componentDidMount fires before socket is ready, now solved, using settimeout function.

componentDidMount(){
   setTimeout(()=>{
     this.socket.on('onreceiveddata', message =>{
        console.log(message);
     });
   }, 500);
}
Ad
source: stackoverflow.com
Ad