What is node js?
Node js is not a language. It is an environment that is open source, cross-platform, and
back-end JavaScript runtime environment that runs on the V8 javascript Engine Developed by Google chrome.
What node js can do?
- Node.js can create, open, read, write, delete, and close files on the server
- Node.js can add, modify, and delete data in your database
- Node.js can generate the dynamic page content
- Node.js can collect form data
What is WebSocket or socket.io?
the socket is a bidirectional connection between the client and server. It is a continuous connection between the server and client until any of the ones have not terminated the connection. It uses the full-duplex protocol.
When we can use a web socket?
- Real-time web application: in real time chat application we need to show the live data on the website or application without loading the page from the client end.
- Gaming application: In a Gaming application, you can see that data is continuously received by the server, and without refreshing the UI
- Chat application: for real-time chat applications between one-to-one users or one-to-many users
How to install web socket in node js application.
Step 1: you should have installed the node js on your computer and created a base project of node js
Step 2: run the command in the terminal
npm i socket.io
step 3: after creating the HTTP server listen to line past the below code in your app.js your group joining request is created and a message emit request is created.
httpServer.listen(3001); const io = require('socket.io')(httpServer, { allowEIO3: true, cors: { origin: true, credentials: true }, }); io.on("connection", async (socket) => { var MyRoomId = "myroomid" socket.on("joinGroup", async (data) => { await socket.join(MyRoomId); console.log(“user successfully connected with room”); }); socket.on("sendMessage", async (data) => { await io.in(MyRoomId).emit("sendMessage_response", { "error": "false", "message": "Message Received successfully", "chat": data.message }); return; }); });
Now let’s understand the code line by line.
Const io holds the reference of socket connection. Which created the socket connection later. io.on(“connection”, async (socket)
After creating the connection we have created an API by which the user will join the group. and Both the users can broadcast their messages from both ends.
socket.on(“joinGroup”, async (data)
After joining the request we need to create another request that will send the message to the group
socket.on(“sendMessage”, async (data)
Now we need to emit the user message in the group so other users can easily read the message that is emitted by other users in the group.
await io.in(MyRoomId).emit("sendMessage_response", { "error": "false", "message": "Message Received successfully", "chat": data.message });
Here we have emitted the JSON in myRoomid
And the listener of the message is the sendMessage_response listener.