Jeff Fohl
Jeff Fohl

Reputation: 2076

How to emit an event in response to an event using socket.io?

I am new to socket.io, and trying to get it to work. I don't know what I am doing wrong here, as it seems super straightforward - yet it is not working. I suppose I am missing something obvious. Hopefully someone else can see what that is.

I am setting up socket.io to work with a node/express server. Here is a simplified version of the test I am trying to do.

Server:

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

/* socket.io test */
io.on('connection', function(socket){
  socket.on('helloServer', function(clientMessage){
    console.log("Server got 'helloServer' event");
    socket.emit('helloClient', { message : "Hi there. We got your message: " + clientMessage.message});
  });
});

The client has a function callServer that is called when a user clicks a button in the UI:

var socket = io.connect('http://localhost');

function callServer() {
  socket.emit('helloServer', { message : "Hello server!" });
}

socket.on('helloClient', function (serverMessage) {
  console.log(serverMessage.message);
});

When I run this code, and click the button that calls callServer, the server does get the event, helloServer, because I see that the console logs the message as expected, but the client never receives a helloClient event. It is as if the socket.emit call within the socket.on response function never gets called.

What am I doing wrong?

Upvotes: 1

Views: 3664

Answers (1)

Renan Caldas
Renan Caldas

Reputation: 56

It appears to be ok. But, just in case, check this answer with all ways of sending data to clients and try use "io.emit" (to send to all clients). Or try sending a string instead of a json object.

I have tried this example here and it is working, just copied and pasted.

Upvotes: 2

Related Questions