{"id":4215,"date":"2023-11-04T23:14:09","date_gmt":"2023-11-04T23:14:09","guid":{"rendered":"http:\/\/localhost:10003\/building-real-time-applications-with-websockets-and-socket-io\/"},"modified":"2023-11-05T05:47:55","modified_gmt":"2023-11-05T05:47:55","slug":"building-real-time-applications-with-websockets-and-socket-io","status":"publish","type":"post","link":"http:\/\/localhost:10003\/building-real-time-applications-with-websockets-and-socket-io\/","title":{"rendered":"Building Real-time Applications with WebSockets and Socket.io"},"content":{"rendered":"
WebSockets are a protocol that allows for real-time, two-way communication between a client and a server. Socket.io is a JavaScript library that simplifies building real-time applications with WebSockets. In this tutorial, we’ll explore how to build a real-time chat application with WebSockets and Socket.io.<\/p>\n
Before we begin, make sure you have the following installed on your machine:<\/p>\n
First, let’s create a new directory for our project and initialize it as a Node.js project:<\/p>\n
mkdir real-time-chat\ncd real-time-chat\nnpm init -y\n<\/code><\/pre>\nNext, let’s install the necessary dependencies:<\/p>\n
npm install express socket.io\n<\/code><\/pre>\nBuilding the server<\/h2>\n
Let’s start by building the server. Create a new file called server.js<\/code> in the root of the project and add the following code:<\/p>\nconst express = require('express');\nconst http = require('http');\nconst socketIO = require('socket.io');\n\nconst app = express();\nconst server = http.Server(app);\nconst io = socketIO(server);\n\nconst PORT = process.env.PORT || 3000;\n\napp.get('\/', (req, res) => {\n res.sendFile(__dirname + '\/index.html');\n});\n\nio.on('connection', (socket) => {\n console.log('a user connected');\n\n socket.on('disconnect', () => {\n console.log('user disconnected');\n });\n});\n\nserver.listen(PORT, () => {\n console.log(`listening on *:${PORT}`);\n});\n<\/code><\/pre>\nThis code creates an Express app, sets up a server with the http<\/code> module, and initializes Socket.IO on the server. The app responds to requests on the root URL by serving up an index.html<\/code> file, and Socket.IO listens for new connections and disconnect events.<\/p>\nBuilding the client<\/h2>\n
Now let’s create the front-end of our chat application. Create a file called index.html<\/code> in the root of the project and add the following code:<\/p>\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n <title>Real-time Chat<\/title>\n<\/head>\n<body>\n <ul id=\"messages\"><\/ul>\n <form action=\"\">\n <input id=\"message-input\" autocomplete=\"off\" \/>\n <button>Send<\/button>\n <\/form>\n\n <script src=\"\/socket.io\/socket.io.js\"><\/script>\n <script>\n const socket = io();\n\n const messageList = document.querySelector('#messages');\n const messageInput = document.querySelector('#message-input');\n const form = document.querySelector('form');\n\n form.addEventListener('submit', (e) => {\n e.preventDefault();\n const message = messageInput.value.trim();\n if (message) {\n socket.emit('chat message', message);\n messageInput.value = '';\n }\n });\n\n socket.on('chat message', (message) => {\n const li = document.createElement('li');\n li.innerText = message;\n messageList.appendChild(li);\n });\n <\/script>\n<\/body>\n<\/html>\n<\/code><\/pre>\nThis code sets up the HTML structure of the chat application, including a form for sending messages and a list for displaying them. It also includes a script tag that loads the Socket.IO client library and sets up the necessary event listeners for sending and receiving messages.<\/p>\n
Testing the application<\/h2>\n
Now that we have our server and client code, let’s test the application. Start the server by running node server.js<\/code> in the terminal, then navigate to `http:\/\/localhost:3000` in your browser.<\/p>\nYou should see the chat interface displayed in the browser window. Open multiple browser tabs or windows to simulate multiple users, and try sending messages to see them appear in real time.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we explored how to build a real-time chat application with WebSockets and Socket.IO. By building a server that listens for new connections and sending messages using the emit()<\/code> method, and a client that listens for messages and sends them using the on()<\/code> and emit()<\/code> methods, we were able to build a real-time chat application with just a few lines of code.<\/p>\nSocket.IO also includes support for rooms, namespaces, and other advanced features that allow for building more complex real-time applications. With Socket.IO and WebSockets, the possibilities for real-time communication on the web are endless.<\/p>\n","protected":false},"excerpt":{"rendered":"
WebSockets are a protocol that allows for real-time, two-way communication between a client and a server. Socket.io is a JavaScript library that simplifies building real-time applications with WebSockets. In this tutorial, we’ll explore how to build a real-time chat application with WebSockets and Socket.io. Prerequisites Before we begin, make sure Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1724,1723,1725,1727,1726,1641,49,1728,1729,1642],"yoast_head":"\nBuilding Real-time Applications with WebSockets and Socket.io - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n