Pjatacsuk Bence
Pjatacsuk Bence

Reputation: 51

(Restify,ReactJS,Node.js) Socket.io client state is disconnected, server logs the connection

I want to try to connect to my Node.js socket.io server from a ReactJS client. The server logs that the user connects / disconnects, however the client seems to timeout (its states say is disconnected).

Here are the relevant snippets: server

    var server = restify.createServer()
const socketio = require('socket.io')
const io= socketio.listen(server)
io.sockets.on('connection', function(socket){  
  console.log('a user connected');
  socket.emit('server event',{'foo':'bar'})

  socket.on('disconnect',function(){
     console.log('user disconnected');
 });
 socket.on('client event',function(data){
    console.log(data)
 })
})

server.listen(8999, function () {
  console.log('%s listening at %s', server.name, server.url)
})

Then I open the app, it logs the 'user connected' event, however the client side seems to be not aware of the connection.

React client side:

   componentDidMount(){

    try {
    this.socket= io.connect('localhost:8999')
    this.socket.on('connected',function(socket){
        console.log('connected')
    })
    this.socket.emit('client event',{value: 'valami tortent'})
    }catch(error){
        console.log(error)
    }
    this.socket.on('server event',function(data){
        console.log(data)
    })
}

I tried debugging the client side, it seems it never receives the packet for connect confirmation.

What seems to be the problem? I tried every connection url types on the client side. The weird thing is that the server is aware of the connection and disconnection.

Upvotes: 0

Views: 343

Answers (2)

Siddharth Sogani
Siddharth Sogani

Reputation: 123

You don't seem to have defined io variable in client side. You have to include client side module for socket io. I hope it works fine once you do so.

Upvotes: 0

Pjatacsuk Bence
Pjatacsuk Bence

Reputation: 51

The problem was, that for restify you have to pass the socketio:true parameter when creating the restify server. So you have to create it like that:

var server = restify.createServer({
    socketio:true
})

Source:

https://github.com/restify/node-restify/issues/717

Upvotes: 1

Related Questions