Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js - Socket.io-client is not connecting to socket.io server

Tags:

I am trying to connect to a socket.io-client using the following code:

Server:

// Load requirements
var http = require('http'),
    io = require('socket.io');

// Create server & socket
var server = http.createServer(function(req, res){

    // Send HTML headers and message
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);

// Add a connect listener
io.sockets.on('connection', function(socket) {

    console.log('Client connected.');

    // Disconnect listener
    socket.on('disconnect', function() {
        console.log('Client disconnected.');
    });
});

Client:

console.log('1');

// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});

console.log('2');

// Add a connect listener
socket.on('connect', function(socket) {
    console.log('Connected!');
});

console.log('3');

I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...

like image 609
exilonX Avatar asked Mar 17 '15 19:03

exilonX


People also ask

Why is socket not connected?

The error message “ERR_SOCKET_NOT_CONNECTED” is instantly solved in the majority of the cases when we flush the sockets on your browser. This will break the connection between any active pages on your browser and you might have to reinitialize everything.

How do I connect socket.io to client side?

var socket = require('socket. io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket'); socket. on('connect', function() { console. log("Successfully connected!"); });

How do I connect socket.io to node js?

In order to do it, you need to create an index. js file and install socket.io and express. You can use the following command: touch index. js && npm install express socket.io && npm install --save-dev nodemon .


2 Answers

Use the same version of socket io client and server. It will work perfectly.

like image 198
Lakin Mohapatra Avatar answered Oct 02 '22 14:10

Lakin Mohapatra


Also you need to add protocol with path.

change

var socket = io.connect('localhost:8080', {reconnect: true});

to

var socket = io.connect('http://localhost:8080', {reconnect: true});
like image 36
jinson Avatar answered Oct 02 '22 14:10

jinson