Socket.IO Client How to Connect?
20,377
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.
Author by
user7337732
Updated on December 25, 2020Comments
-
user7337732 over 3 years
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 over 7 yearsCould you provide an example website where this works on your computer?
-
user7337732 over 7 yearsThanks. 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.