40

I am trying to get started with node.js and socket.io.
I have a very (very) simple client-server test application and i can't get it to work.
The system is set up on a windows machine with an apache server.
The apache is running on port 81 and the the socket.io is set up to listen to port 8001

Server - server.js

var io = require('socket.io').listen(8001);

io.sockets.on('connection', function (socket) {
    console.log('\ngot a new connection from: ' + socket.id + '\n');
});

Client - index.html

<!DOCTYPE html>
<html>
<head>
    <title>node-tests</title>
    <script type="text/javascript" src="http://localhost:8001/socket.io/socket.io.js">    </script>
    <script type="text/javascript">
        var socket = io.connect('http://localhost', { port: 8001 });

        socket.on('connect', function () {
            alert('connect');
        });

        socket.on('error', function (data) {
            console.log(data || 'error');
        });

        socket.on('connect_failed', function (data) {
            console.log(data || 'connect_failed');
        });
    </script>
</head>
<body>

</body>
</html>

After starting my server using node server.js the standard (expected) output is written to the server console:

info: socket.io started

When I open index.html in the browser (chrome in my case - didn't test on other browsers) the following log is written to the server console:

info: socket.io started
debug: served static content /socket.io.js
debug: client authorized
info: handshake authorized 9952353481638352052
debug: setting request GET /socket.io/1/websocket/9952353481638352052
debug: set heartbeat interval for client 9952353481638352052
debug: client authorized for

got a new connection from: 9952353481638352052

debug: setting request GET /socket.io/1/xhr-polling/9952353481638352052?t=1333635235315
debug: setting poll timeout
debug: discarding transport
debug: cleared heartbeat interval for client 9952353481638352052
debug: setting request GET /socket.io/1/jsonp-polling/9952353481638352052?t=1333635238316&i=0
debug: setting poll timeout
debug: discarding transport
debug: clearing poll timeout
debug: clearing poll timeout
debug: jsonppolling writing io.j[0]("8::");
debug: set close timeout for client 9952353481638352052
debug: jsonppolling closed due to exceeded duration
debug: setting request GET /socket.io/1/jsonp-polling/9952353481638352052?t=1333635258339&i=0
...
...
...

In the browsers console I get:

connect_failed

So it seems like the client is reaching the server and trying to connect, and the server is authorizing the handshake but the connect event is never fired in the client, instead the connect method reaches its connect timeout and max reconnection attempts and gives up returning connect_failed.

Any help\insight on this would be helpful.

Thank you

kfiroo
  • 1,913
  • 2
  • 15
  • 18
  • 8
    Try just using io.connect() it can infer the URL and port from the url you're on. I have run into problems in the past with things in io.connect not working like I would expect them to. – Timothy Strimple Apr 05 '12 at 18:45
  • @TimothyStrimple Thank you Tim! **Working again on heroku (Cedar) and localhost**! – AmpT Apr 10 '14 at 23:34

7 Answers7

16

Make sure that both client and server have same major version of socket.io. For example, combination of socket.io@2.3.0 on server and socket.io-client@3.x.x at client leads to this case and the 'connect' event is not dispatched.

justlo0king
  • 341
  • 2
  • 4
10
//Client side
<script src="http://yourdomain.com:8001/socket.io/socket.io.js"></script>
var socket = io.connect('http://yourdomain.com:8001');

//Server side
var io = require('socket.io').listen(8001);
io.sockets.on('connection',function(socket) {
`console.log('a user connected');`
});

Client side: The client side code requests the client version of socket IO from the same file that gives you server side socketIO. Var socket will now have all the methods that are available with socketIO, such as socket.emit or socket.on

Server Side: same as client side, making the socketIO methods available for use under var io.

jDubs
  • 131
  • 1
  • 6
4

Change in the frontend (client):

var socket = io.connect(http://myapp.herokuapp.com);

to

var socket = io.connect();

After many hours of dealing with various clients (Chrome, Firefox browsers and Phonegap app) that did not register connection to the server properly (i.e. the server registered the websocket connection successfully in its logs, but the frontend did not register the connection event), I tried @Timothy's solution from the comments and now everything works again on heroku and on localhost.

AmpT
  • 2,146
  • 1
  • 24
  • 25
2

With socketio 2.3.0 you have to use socket.on('connect')

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io({
        transports: ['polling']
    });
    console.log("created",socket);
    socket.on('connect', function(data){ // <-- this works
        console.log("socket ON connect",data);
    });
    socket.on('connection', function(data){ // <-- this fails
        console.log("socket ON connection",data);
    });

</script>
Stepan Yakovenko
  • 8,670
  • 28
  • 113
  • 206
  • And on 2.1.0. I think it's "connect" on socket-client 2+, however I can't confirm that right now. – Mike K May 14 '20 at 08:49
0

Use autoConnect: false option while creating: io(... { autoConnect: false }), subscribe on your events and invoke io.connect().

-1

Try the following:

Change

var socket = io.connect('http://localhost', { port: 8001 });

to

var socket = io.connect('http://localhost:8001');
zallarak
  • 5,287
  • 7
  • 38
  • 54
-1

Try using this:

Server.js

var http = require("http").createServer(), io = require("socket.io").listen(http);

http.listen(8001);

io.sockets.on("connection", function(socket){
    console.log("Connected!");
    socket.emit("foo", "Now, we are connected");
});

index.html

<script src="http://localhost:8001/socket.io/socket.io.js"></script>
<script>
     var i = io.connect("http://localhost:5001");
     i.on("foo", function(bar){
         console.log(bar);
     })
</script>
ZeroBryan
  • 9
  • 3