Categories
JavaScript Answers

How to add a client for a socket.io server with Node.js?

Spread the love

Sometimes, we want to add a client for a socket.io server with Node.js.

In this article, we’ll look at how to add a client for a socket.io server with Node.js.

How to add a client for a socket.io server with Node.js?

To add a client for a socket.io server with Node.js, we can use the socket.io-client package.

To install, it we run

npm i socket.io-client

Then use the package by writing

const io = require('socket.io-client');
const socket = io.connect('http://localhost:3000', {
  reconnect: true
});

socket.on('connect', (socket) => {
  console.log('Connected!');
});
socket.emit('ch01', 'me', 'test msg');

We connect by calling io.connect with the server ID address.

Then we call socket.on with 'connect' to listen for connection success.

And then we call socket.emit to send a message to a channel.

Next, we add our server by writing

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

io.on('connection', (socket) => {
  console.log('connection');

  socket.on('ch01', (from, msg) => {
    console.log('message', from, ' saying ', msg);
  });

});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

to call io.on with 'connection' to listen for client connections.

And then we call socket.one with 'ch01' to listen for messages on room 'ch01'.

Conclusion

To add a client for a socket.io server with Node.js, we can use the socket.io-client package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *