socket.io - .on not working on client side

Viewed 903

I have some very basic code that uses socket.io

Client

var socket = io();

// Do some stuff...

socket.emit('hello', 'please like me');

// Wait for a response
socket.on('hello back!', function(msg) {
    console.log('Yay, he replied:', msg);
});

Server

var app = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket) {
    console.log('a user connected');

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

    socket.on('hello', function() {
        // Code to decide wether or not I like the client
        // ...
        // I do like the client!
        socket.emit('hello back!', 'how are you');
        console.log('I said hello back!');
    });
});

Hopefully you managed to get the picture. So ideally, this would happen:

  1. Client connects
  2. After a while, client emits hello
  3. Server sees this, emits hello back!
  4. Client notices the hello back! event
  5. Everyone is happy!

But this isn't the case for me unfortunately. Instead, steps 1-3 work perfectly. But when you reach step 4 and 5, things start to fall apart. Client never logs anything after hello back! event is emitted.

This is not my full code, I figured it would make it easier for you to understand it. It's very possible that I've made some silly mistake somewhere, maybe without including it in this code. But please let me know if there is anything fundamentally wrong with what I am doing.

Cheers

1 Answers

This is a few years old, but in case anyone stumbles across this in the future:

My problem had nothing to do with my code shown above. Instead, it was a configuration error.

I was hosting my project on glitch.com who state that they support websockets, but the error was caused because the server was not able to get across to the client (client never received any data from server at all after websocket connection was opened).

This was an error that I had in 2018 with glitch.com, and I know that other people have had it too. It also seemed to be related somehow to websockets connecting via a domain name and with SSL, but I can't recall the exact circumstances.

Related