{"id":28705,"date":"2024-04-17T03:46:02","date_gmt":"2024-04-17T02:46:02","guid":{"rendered":"https:\/\/nelkodev.com\/blog\/construye-tu-propia-aplicacion-de-chat-en-tiempo-real-con-socket-io\/"},"modified":"2024-06-03T18:44:04","modified_gmt":"2024-06-03T17:44:04","slug":"construye-tu-propia-aplicacion-de-chat-en-tiempo-real-con-socket-io","status":"publish","type":"post","link":"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/","title":{"rendered":"Build Your Own Real-Time Chat Application with Socket.IO"},"content":{"rendered":"<p>In the world of modern web applications, real-time interaction has become an indispensable feature. Whether it&#039;s social media, online gaming, or chat apps, users expect instant communications. Today we&#039;re going to dive into how you can build your own chat application using Socket.IO, a powerful JavaScript library designed to facilitate real-time, two-way communication between servers and web clients.<\/p>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_80 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #ffffff;color:#ffffff\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewbox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #ffffff;color:#ffffff\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewbox=\"0 0 24 24\" version=\"1.2\" baseprofile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#%C2%BFQue_es_SocketIO_y_por_que_usarlo\" >What is Socket.IO and why use it?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Configuracion_del_entorno_de_desarrollo\" >Development environment configuration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Instalacion_de_SocketIO\" >Installing Socket.IO<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Creando_el_servidor\" >Creating the server<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Configurando_el_Cliente\" >Configuring the Client<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Probando_la_Aplicacion\" >Testing the Application<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/nelkodev.com\/en\/blog\/build-your-own-real-time-chat-app-with-socket-io\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h3><span class=\"ez-toc-section\" id=\"%C2%BFQue_es_SocketIO_y_por_que_usarlo\"><\/span>What is Socket.IO and why use it?<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Socket.IO is a library that enables real-time, bidirectional, event-based communication between the browser and the server. It is made up of two parts: a server that integrates with Node.js and a client that runs in the browser. What makes Socket.IO unique is its ability to automatically handle disconnecting, reconnecting, and saving messages \u2013 essential features for any chat application.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Configuracion_del_entorno_de_desarrollo\"><\/span>Development environment configuration<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Before we start coding, we need to set up our development environment. Make sure you have Node.js installed on your system as it will be required to run our chat server. You can download and install it from <a href=\"https:\/\/nodejs.org\/\" rel=\"nofollow noopener\" target=\"_blank\">nodejs.org<\/a>.<\/p>\n<p>Once Node.js is installed, we can create a new directory for our chat project and navigate to it using the terminal:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">mkdir chat-app cd chat-app<\/code><\/pre>\n<p>Inside the directory, initialize a new Node.js project:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">npm init -y<\/code><\/pre>\n<p>This will create a new file <code>package.json<\/code>, which will handle the dependencies of our project.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Instalacion_de_SocketIO\"><\/span>Installing Socket.IO<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To use Socket.IO, we need to install it on both the server and client side. We will start by installing the server part with npm:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">npm install socket.io<\/code><\/pre>\n<p>Additionally, we will need <code>express<\/code> to configure the HTTP server:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">npm install express<\/code><\/pre>\n<h3><span class=\"ez-toc-section\" id=\"Creando_el_servidor\"><\/span>Creating the server<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Now that we have our dependencies installed, let&#039;s create a file called <code>server.js<\/code>:<\/p>\n<pre><code class=\"&quot;language-javascript&quot;\">const express = require(&#039;express&#039;); const http = require(&#039;http&#039;); const socketIo = require(&#039;socket.io&#039;); const app = express(); const server = http.createServer(app); const io = socketIo(server); app.get(&#039;\/&#039;, (req, res) =&gt; { res.sendFile(__dirname + &#039;\/index.html&#039;); }); io.on(&#039;connection&#039;, (socket) =&gt; { console.log(&#039;A user has connected&#039;); socket.on(&#039;chat message&#039;, (msg) =&gt; { io.emit(&amp;#039 ;chat message&#039;, msg); socket.on(&#039;disconnect&#039;, () =&gt; { console.log(&#039;A user has disconnected&#039;); const PORT = process.env.PORT || 3000; server.listen(PORT, () =&gt; { console.log(`Server running on port ${PORT}`); });<\/code><\/pre>\n<p>This code sets up a basic server that can send and receive messages through Socket.IO. When a client connects, a message is displayed on the console, and when a chat message is sent, it is broadcast to all connected users.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Configurando_el_Cliente\"><\/span>Configuring the Client<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Create a file <code>index.html<\/code> in the main directory:<\/p>\n<pre><code class=\"&quot;language-html&quot;\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Chat with Socket.IO&lt;\/title&gt;\n&lt;style&gt;\n  ul { list-style-type: none; margin: 0; padding: 0; }\n  li { padding: 8px; margin-bottom: 2px; background-color: #f3f3f3; }\n&lt;\/style&gt;\n&lt;\/head&gt;\n&lt;body&gt;\n&lt;ul id=&quot;messages&quot;&gt;&lt;\/ul&gt;\n&lt;form id=&quot;form&quot; action=&quot;&quot; data-trp-original-action=&quot;&quot;&gt;\n&lt;input id=&quot;input&quot; autocomplete=&quot;off&quot; \/&gt;&lt;button&gt;Send&lt;\/button&gt;\n&lt;input type=&quot;hidden&quot; name=&quot;trp-form-language&quot; value=&quot;en&quot;\/&gt;&lt;\/form&gt;\n\n&lt;script src=&quot;\/socket.io\/socket.io.js&quot;&gt;&lt;\/script&gt;\n&lt;script&gt;\n  var socket = io();\n\n  var form = document.getElementById(&#039;form&#039;);\n  var input = document.getElementById(&#039;input&#039;);\n\n  form.addEventListener(&#039;submit&#039;, function(e) {\n    e.preventDefault();\n    if (input.value) {\n      socket.emit(&#039;chat message&#039;, input.value);\n      input.value = &#039;&#039;;\n    }\n  });\n\n  socket.on(&#039;chat message&#039;, function(msg) {\n    var item = document.createElement(&#039;li&#039;);\n    item.textContent = msg;\n    document.getElementById(&#039;messages&#039;).appendChild(item);\n    window.scrollTo(0, document.body.scrollHeight);\n  });\n&lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;<\/code><\/pre>\n<p>This HTML code includes a basic form for sending messages and a list for displaying them. It uses JavaScript to handle form submission and to update the page when messages are received.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Probando_la_Aplicacion\"><\/span>Testing the Application<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>To see our chat app in action, simply start the server:<\/p>\n<pre><code class=\"&quot;language-bash&quot;\">node server.js<\/code><\/pre>\n<p>Open your browser and visit <code>http:\/\/localhost:3000<\/code>. You should see your chat app working and be able to send and receive messages in real time.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>And that&#039;s it! You&#039;ve created a basic chat app using Socket.IO. These tools are not only powerful but also flexible, enabling a wide range of real-time functionality in modern web applications.<\/p>\n<p>To learn more about web development and other technologies, visit <a href=\"https:\/\/nelkodev.com\/en\/\">nelkodev.com<\/a> where we continually add new tutorials and developer tips. Also, if you have any questions or need additional help, feel free to contact me via <a href=\"https:\/\/nelkodev.com\/en\/contact\/\">https:\/\/nelkodev.com\/contacto<\/a>.<\/p>\n<p>I hope this tutorial was useful to you and inspires you to explore more about real-time programming and web application development. Until next time!<\/p>","protected":false},"excerpt":{"rendered":"<p>In the world of modern web applications, real-time interaction has become an indispensable feature. Whether it\u2019s social media, online games, or chat apps, users expect instant communications. Today we\u2019re going to dive into how you can build your own chat application using Socket.IO, a powerful library for web applications that can be used to communicate with other [\u2026]<\/p>","protected":false},"author":1,"featured_media":28706,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[420,2207],"tags":[874,205,1391,90,1643,2208,101,1766,399,1769,1897,400],"class_list":["post-28705","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-nodejs","tag-aplicacion","tag-blog","tag-chat","tag-con","tag-construye","tag-nodejs","tag-programacion","tag-propia","tag-real","tag-red","tag-socket-io","tag-tiempo"],"_links":{"self":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28705","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/comments?post=28705"}],"version-history":[{"count":0,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/posts\/28705\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media\/28706"}],"wp:attachment":[{"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/media?parent=28705"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/categories?post=28705"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nelkodev.com\/en\/wp-json\/wp\/v2\/tags?post=28705"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}