Using socket.io with Node.js

socket.io

In this post we’ll guide you to use socket.io with node.js  in simple way.

Initialize a node project

run npm init -y to initialize a node project

Install socket.io on node

run this code in your terminal of your project

npm install socket.io

Install express

run this code in your terminal of your project

npm install express

Creating server and socket listener

create server.js file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const express = require("express");
const app = express();
const socketio = require("socket.io");

app.use(express.static(__dirname + "/public"));

const expressServer = app.listen(5000);

const io = socketio(expressServer, {
  cors: {
    origin: "http://127.0.0.1:8080",
    method: ["GET", "POST"],
    credential: true,
  },
});

io.on("connection", (socket) => {
  socket.emit("messageFromServer", "connection established");
  socket.on("dataToServer", (data) => console.log(data));
});

Creating client file

inside public folder create chat.html file

1
2
3
4
5
6
7
8
<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io("http://localhost:5000");
  socket.on("messageFromServer", (message) => {
    console.log(message);
    socket.emit("dataToServer", { data: "Data sent from the client" });
  });
</script>

Running server

run node server.js to run server

Running client

goto http://localhost:4000/chat

you can see console displaying message from server and client to each other respectively.

You can get this blog post on Idea Breed Blog page

-By Sajan Dhakal

Share on facebook
Share on twitter
Share on linkedin

Leave A Comment

Related Posts

Featured Posts
Author

Anish Lamsal

Frontend Developer

Computer Engineer pursuing his passion in blogging.