Categories
JavaScript Answers

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

Spread the love

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

For instance, on the Node.js client, we add

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");

to connect to localhost:3000 with io.connect.

We call on to listen for connection events.

And we call emit to emit the 'CH01' event with 'me' and 'test msg' as the content.

On server side, we write

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("MSG", from, " saying ", msg);
  });
});

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

to listen for the 'CH01' event with on`.

We listen for the connection event with on.

And we get the values from emit on client side from the parameters.

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 *