4

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!

user7337732
  • 71
  • 1
  • 1
  • 5

1 Answers1

6

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.

peteb
  • 18,552
  • 9
  • 50
  • 62
  • Could you provide an example website where this works on your computer? – user7337732 Dec 25 '16 at 06:13
  • 1
    Thanks. I ran the server side code, then opened a new terminal and ran the client side code but nothing. I just want to connect to a website which I know uses socket.io -- it's not my website -- and start sending it data. – user7337732 Dec 25 '16 at 06:31