2

I have created a small server for communication using node.js and socket io

Server:

var express = require('/usr/local/lib/node_modules/express') var io = require('/usr/local/lib/node_modules/socket.io'); var server = express.createServer(); server.listen(8888,'localhost'); io = io.listen(server); io.of("namespace").on('connection', function(client){ client.emit("message",'connection successful'); client.on('message', function(m){ console.log("received message"+m); client.broadcast(m); }); }); 

Client:

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Comet Test</title> <script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script> </head> <body> <p><a id='customAlert' href="#" onclick='sendMessage("customAlert")'>publish customAlert</a></p> <p><a id='customAlert2' href="#" onclick='sendMessage("customAlert2")'>publish customAl <script type="text/javascript"> // Start the socket var socket = io.connect('http://localhost:8888/namespace'); socket.on('error', function (reason){ console.error('Unable to connect Socket.IO', reason); }); socket.on('message', function(msg){ console.log(msg); }); function sendMessage(m) { console.log("sending message"+m); socket.emit("message",m); } </script> </body> 

Communication does not happen, am I doing something wrong here?

2
  • Have you checked if io.connect is trying to connect to port 8888 on the server? Commented Oct 21, 2011 at 17:34
  • is there a way to handle if io.connect fails to connect ? Commented Apr 25, 2012 at 12:03

1 Answer 1

5

If your server is listening on port 8888, you need the client to connect to the server on port 8888.

The following line in your client code:

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

Should read:

 var socket = io.connect('http://localhost:8888/namespace'); 
Sign up to request clarification or add additional context in comments.

3 Comments

the html file is accessed through apache, so should this create any issues.
I have edited my code to include the new changes, now i start my server and when i open the html in the browser the server gets a client connect request and authorisation is successful, but when I try to send some messages the messages are lost and not caught by the server
You could try adding event listeners both server and client-side for both connection and disconnection events. This might give you a clearer picture of whether the connection is still alive when sending messages.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.