Using socket.io With Node.js
1 Min. Read
May 12, 2021
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