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?