{"id":5103,"date":"2025-04-14T15:00:00","date_gmt":"2025-04-14T09:30:00","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5103"},"modified":"2025-04-14T15:00:00","modified_gmt":"2025-04-14T09:30:00","slug":"building-a-chat-application-using-websockets-and-socket-io","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/building-a-chat-application-using-websockets-and-socket-io\/","title":{"rendered":"Building a Chat Application using WebSockets and Socket.IO"},"content":{"rendered":"<p>WebSockets provide a persistent connection between a client and a server, enabling real-time, bidirectional communication. <span>This makes them ideal for applications like chat, online games, and live dashboards. Socket.IO is a library that simplifies the use of WebSockets, providing fallbacks for older browsers and adding useful features like rooms and namespaces.<\/span><\/p>\n<p><\/p>\n<p>In this blog post, we&#8217;ll walk through building a basic chat application using Node.js, Express, and Socket.IO.<\/p>\n<p><\/p>\n<p><strong>Prerequisites:<\/strong><\/p>\n<ul>\n<li>Node.js and npm installed.<\/li>\n<\/ul>\n<p><\/p>\n<p><strong>Setting up the Project:<\/strong><\/p>\n<ol>\n<li><strong>Create a project directory:<\/strong><\/li>\n<li><span>Bash<\/span><\/li>\n<li><\/li>\n<\/ol>\n<pre class=\"ql-syntax\">mkdir real-time-chat\ncd real-time-chat\n<\/pre>\n<ol>\n<li><strong>Initialize a Node.js project:<\/strong><\/li>\n<li><span>Bash<\/span><\/li>\n<li><\/li>\n<\/ol>\n<pre class=\"ql-syntax\">npm init -y\n<\/pre>\n<ol>\n<li><strong>Install Express and Socket.IO:<\/strong><\/li>\n<li><span>Bash<\/span><\/li>\n<li><\/li>\n<\/ol>\n<pre class=\"ql-syntax\">npm install express socket.io\n<\/pre>\n<p><\/p>\n<p><strong>Creating the Server (server.js):<\/strong><\/p>\n<pre class=\"ql-syntax\">const express = require('express');\nconst http = require('http');\nconst { Server } = require('socket.io');\n\nconst app = express();\nconst server = http.createServer(app);\nconst io = new Server(server);\n\n\/\/ Serve static files (HTML, CSS, JS) from the 'public' directory\napp.use(express.static('public'));\n\nio.on('connection', (socket) =&gt; {\n  console.log('A user connected');\n\n  socket.on('chat message', (msg) =&gt; {\n    io.emit('chat message', msg); \/\/ Broadcast the message to all connected clients\n  });\n\n  socket.on('disconnect', () =&gt; {\n    console.log('User disconnected');\n  });\n});\n\nconst PORT = process.env.PORT || 3000;\n\nserver.listen(PORT, () =&gt; {\n  console.log(`Server listening on port ${PORT}`);\n});\n<\/pre>\n<p><\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>We create an Express application and an HTTP server.<\/li>\n<li>We initialize Socket.IO with the HTTP server.<\/li>\n<li><code>app.use(express.static('public'))<\/code> serves static files from the <code>public<\/code> directory.<\/li>\n<li><code>io.on('connection', (socket) =&gt; { ... })<\/code> handles new client connections.<\/li>\n<li><code>socket.on('chat message', (msg) =&gt; { ... })<\/code> listens for &#8216;chat message&#8217; events from the client and broadcasts them to all connected clients using <code>io.emit()<\/code>.<\/li>\n<li><code>socket.on('disconnect', () =&gt; { ... })<\/code> handles client disconnections.<\/li>\n<\/ul>\n<p><\/p>\n<p><strong>Creating the Client (public\/index.html):<\/strong><\/p>\n<p><span>HTML<\/span><\/p>\n<p><\/p>\n<pre class=\"ql-syntax\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n  &lt;title&gt;Chat Application&lt;\/title&gt;\n  &lt;style&gt;\n    #messages { list-style-type: none; margin: 0; padding: 0; }\n    #messages li { padding: 5px 10px; }\n    #messages li:nth-child(odd) { background: #eee; }\n    #form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }\n    #input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }\n    #button { background: rgb(130, 224, 255); border: none; padding: 10px; width: 9%; }\n  &lt;\/style&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n  &lt;ul id=\"messages\"&gt;&lt;\/ul&gt;\n  &lt;form id=\"form\" action=\"\"&gt;\n    &lt;input type=\"text\" id=\"input\" autocomplete=\"off\" \/&gt;&lt;button&gt;Send&lt;\/button&gt;\n  &lt;\/form&gt;\n  &lt;script src=\"\/socket.io\/socket.io.js\"&gt;&lt;\/script&gt;\n  &lt;script&gt;\n    const socket = io();\n    const form = document.getElementById('form');\n    const input = document.getElementById('input');\n    const messages = document.getElementById('messages');\n\n    form.addEventListener('submit', (e) =&gt; {\n      e.preventDefault();\n      if (input.value) {\n        socket.emit('chat message', input.value);\n        input.value = '';\n      }\n    });\n\n    socket.on('chat message', (msg) =&gt; {\n      const item = document.createElement('li');\n      item.textContent = msg;\n      messages.appendChild(item);\n      window.scrollTo(0, document.body.scrollHeight);\n    });\n  &lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/pre>\n<p><\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li>We include the Socket.IO client library (<code>\/socket.io\/socket.io.js<\/code>).<\/li>\n<li>We initialize a Socket.IO connection using <code>io()<\/code>.<\/li>\n<li>We listen for form submissions and emit &#8216;chat message&#8217; events to the server.<\/li>\n<li>We listen for &#8216;chat message&#8217; events from the server and append them to the message list.<\/li>\n<\/ul>\n<p><\/p>\n<p><strong>Running the Application:<\/strong><\/p>\n<ol>\n<li>Create a <code>public<\/code> directory in your project root.<\/li>\n<li>Save the <code>index.html<\/code> file in the <code>public<\/code> directory.<\/li>\n<li>Save the <code>server.js<\/code> file in your project root.<\/li>\n<li>Run the server:<\/li>\n<li><span>Bash<\/span><\/li>\n<li><\/li>\n<\/ol>\n<pre class=\"ql-syntax\">node server.js\n<\/pre>\n<ol>\n<li>Open your browser and navigate to <code>http:\/\/localhost:3000<\/code>.<\/li>\n<li>Open multiple browser tabs or windows to see the real-time chat in action.<\/li>\n<\/ol>\n<p><\/p>\n<p><strong>Further Enhancements:<\/strong><\/p>\n<ul>\n<li><strong>Usernames:<\/strong> Add username functionality to identify users.<\/li>\n<li><strong>Rooms:<\/strong> Implement chat rooms for different topics or groups.<\/li>\n<li><strong>Private Messages:<\/strong> Allow users to send private messages to each other.<\/li>\n<li><strong>Typing Indicators:<\/strong> Show when a user is typing.<\/li>\n<li><strong>Message History:<\/strong> Store and display previous messages.<\/li>\n<li><strong>Styling:<\/strong> Enhance the UI with CSS.<\/li>\n<li><strong>Deployment:<\/strong> Deploy your application to a hosting platform.<\/li>\n<\/ul>\n<p><\/p>\n<p>Socket.IO makes it easy to build real-time applications with WebSockets. By leveraging its features, you can create engaging and interactive experiences for your users.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>WebSockets provide a persistent connection between a client and a server, enabling real-time, bidirectional communication. This makes them ideal for applications like chat, online games, and live dashboards. Socket.IO is a library that simplifies the use of WebSockets, providing fallbacks for older browsers and adding useful features like rooms and namespaces. In this blog post,<\/p>\n","protected":false},"author":67,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[231],"tags":[226],"class_list":["post-5103","post","type-post","status-publish","format-standard","category-article","tag-frontend"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5103","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/67"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5103"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5103\/revisions"}],"predecessor-version":[{"id":5106,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5103\/revisions\/5106"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5103"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5103"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5103"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}