Socket.IO Client How to Connect?

user7337732 picture user7337732 · Dec 25, 2016 · Viewed 16.4k times · Source

I was following the second example here: https://github.com/socketio/socket.io-client

and trying to connect to a website that uses websockets, using socket.io-client.js in node.

My code is as follows:

var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');

socket.on('connect', function() {
    console.log("Successfully connected!");
});

Unfortunately, nothing gets logged.

I also tried:

var socket = require('socket.io-client')('http://website.com/');

socket.on('connect', function() {
    console.log("Successfully connected!");
});

but nothing.

Please tell me what I'm doing wrong. Thank you!

Answer

peteb picture peteb · Dec 25, 2016

Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.

Socket.io Client

const io = require('socket.io-client');
const socket = io.connect('http://website.com');

socket.on('connect', () => {
  console.log('Successfully connected!');
});

Socket.io Server w/ Express

const express = require('express');

const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);

const port = process.env.PORT || 1337;

server.listen(port, () => {
    console.log(`Listening on ${port}`);
});

io.on('connection', (socket) => {
    // add handlers for socket events
});

Edit

Added Socket.io server code example.