Beginner
Beginner

Reputation: 202

Socket.io Server Emit only works after server restart

Please forgive me if this comes out to be a a real stupid question.
I was watching a tutorial on Socket.io and everything worked great. So I wanted to try it in a reactjs app. But the problem is that while I am able to emit from client side, I'm not able to do it from server side.
The emit works if I restart the server and what I mean by that is that when I run the application, initially server logs the message and after the restart, the client logs the message.

client side

import React, { Component } from 'react';
import socket from '../socketConfig'

class App extends Component {
    componentDidMount(){
        socket.on('hello',(data)=>{
            console.log(data);
        })
        socket.emit('call','this is from client');
    }
    render(){
        return (
            <div></div>
        )
    }
}
export default App;

socketConfig

import openSocket from 'socket.io-client';

const socket = openSocket("http://localhost:4000/");

export default socket;

Server side

var express = require('express');

var socket = require('socket.io');
var app = express();
var server = app.listen(4000, function () {
  console.log('listening for requests on port 4000,');
});

app.use(express.static('public'));

var io = socket(server);

io.sockets.on('connection', (socket) => {
  socket.emit('hello','msg from server');
  socket.on('call', (data)=>{console.log(data)});
}

Upvotes: 1

Views: 1001

Answers (2)

Beginner
Beginner

Reputation: 202

So the problem was that I was listening to events in copmponentDidMount() but using componentDidUpdate() solved the problem.

App Component

    state = {
        socket:null
    }
    componentDidMount(){
        this.setState({
            socket:io("http://localhost')
        })  

    }
    componentDidUpdate(){
        let sokt = this.state.socket;
        sokt.on('connect',()=>{
            sokt.on('hello',(data)=>console.log(data)); //logged: msg from server
            sokt.emit('call',"This is from client"); //logged: This is from client
        })
    }

But I'm not sure if this is correct way to do this

Upvotes: 0

adrum
adrum

Reputation: 71

I think the issue might be in the url you are using - socket.io can be finicky since it isn't strictly a web socket, it's a wrapper around long polling and websockets. So you may have to specify which transport to use, since the socket handling is done on the same port as the http handling.

Try this url from the client side:

ws://localhost:4000/socket.io/?EIO=3&transport=websocket

Upvotes: 1

Related Questions