{"id":226,"date":"2024-02-06T23:45:10","date_gmt":"2024-02-06T23:45:10","guid":{"rendered":"https:\/\/davagordon.co.uk\/blog\/?p=226"},"modified":"2024-05-12T02:31:18","modified_gmt":"2024-05-12T01:31:18","slug":"unlock-real-time-potential-building-a-collaborative-app-with-websockets","status":"publish","type":"post","link":"https:\/\/davagordon.co.uk\/blog\/unlock-real-time-potential-building-a-collaborative-app-with-websockets\/","title":{"rendered":"Unlock Real Time Potential: Building a Collaborative App with WebSockets"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The development of real time tools has increased among modern web professionals. WebSockets is a useful tool that enables real time communication between clients and servers, whether you are developing a communication image tool, a live chat application, or a collaborative document editor In this article we will walk you through a they use WebSockets to make it into real time collaboration software.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How does WebSockets work?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">WebSockets are a complete dual communication mechanism over a single long-lived connection, allowing clients and servers to exchange data in real time. WebSockets are ideal for applications that need to be updated immediately because they allow two-way communication, which is not possible with ordinary HTTP requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Before we begin the tutorial, make sure you have the following prerequisites.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Basic knowledge of HTML, CSS, and JavaScript.<\/li>\n\n\n\n<li><a href=\"https:\/\/nodejs.org\/\" target=\"_blank\" rel=\"noopener\" title=\"Node.js\">Node.js<\/a> and npm installed on your development machine.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Set Up Your Project<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new project directory and initialize a Node.js project. Open your terminal and run the following commands:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nmkdir collab-app\ncd collab-app\nnpm init -y\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Install the necessary packages:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnpm install express socket.io\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Create an <code>index.js<\/code> file to start building your server:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/ index.js\n\nconst express = require(&#039;express&#039;);\nconst http = require(&#039;http&#039;);\nconst socketIO = require(&#039;socket.io&#039;);\n\nconst app = express();\nconst server = http.createServer(app);\nconst io = socketIO(server);\n\napp.get(&#039;\/&#039;, (req, res) =&gt; {\n  res.sendFile(__dirname + &#039;\/index.html&#039;);\n});\n\nserver.listen(3000, () =&gt; {\n  console.log(&#039;Server is running on http:\/\/localhost:3000&#039;);\n});\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><h2 style=\"border: 0px solid rgb(217, 217, 227); box-sizing: border-box; --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgba(69,89,164,.5); --tw-ring-offset-shadow: 0 0 transparent; --tw-ring-shadow: 0 0 transparent; --tw-shadow: 0 0 transparent; --tw-shadow-colored: 0 0 transparent; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; font-size: 1.5em; font-weight: 600; margin: 2rem 0px 1rem; line-height: 1.33333; font-family: S\u00f6hne, ui-sans-serif, system-ui, -apple-system, &quot;Segoe UI&quot;, Roboto, Ubuntu, Cantarell, &quot;Noto Sans&quot;, sans-serif, &quot;Helvetica Neue&quot;, Arial, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Segoe UI Symbol&quot;, &quot;Noto Color Emoji&quot;;\">Step 2: Create the HTML file<\/h2><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create a simple HTML file (<code>index.html<\/code>) to serve as the entry point for your application:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;!-- index.html --&gt;\n\n&lt;!-- ... (previous HTML code) --&gt;\n\n&lt;body&gt;\n  &lt;h1&gt;Welcome to the Collab App&lt;\/h1&gt;\n\n  &lt;!-- Form for setting the username --&gt;\n  &lt;form id=&quot;username-form&quot;&gt;\n    &lt;label for=&quot;username&quot;&gt;Enter your username:&lt;\/label&gt;\n    &lt;input type=&quot;text&quot; id=&quot;username&quot; required&gt;\n    &lt;button type=&quot;submit&quot;&gt;Set Username&lt;\/button&gt;\n  &lt;\/form&gt;\n\n  &lt;!-- Your collaborative app interface goes here --&gt;\n  &lt;div id=&quot;messages-container&quot;&gt;&lt;\/div&gt;\n  &lt;form id=&quot;message-form&quot;&gt;\n    &lt;input type=&quot;text&quot; id=&quot;message-input&quot; placeholder=&quot;Type your message...&quot; required&gt;\n    &lt;button type=&quot;submit&quot;&gt;Send&lt;\/button&gt;\n  &lt;\/form&gt;\n\n  &lt;script src=&quot;\/socket.io\/socket.io.js&quot;&gt;&lt;\/script&gt;\n  &lt;script src=&quot;\/main.js&quot;&gt;&lt;\/script&gt;\n&lt;\/body&gt;\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Step 3: Implement WebSocket Communication<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a <code>main.js<\/code> file to handle WebSocket communication:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/ main.js\n\nconst socket = io();\n\n\/\/ DOM elements\nconst messageForm = document.getElementById(&#039;message-form&#039;);\nconst messageInput = document.getElementById(&#039;message-input&#039;);\nconst messagesContainer = document.getElementById(&#039;messages-container&#039;);\n\n\/\/ Function to append messages to the UI\nfunction appendMessage(username, message) {\n  const messageElement = document.createElement(&#039;div&#039;);\n  messageElement.innerHTML = `&lt;strong&gt;${username}:&lt;\/strong&gt; ${message}`;\n  messagesContainer.appendChild(messageElement);\n}\n\n\/\/ Event listener for form submission (sending messages)\nmessageForm.addEventListener(&#039;submit&#039;, (event) =&gt; {\n  event.preventDefault();\n  const message = messageInput.value.trim();\n  if (message !== &#039;&#039;) {\n    socket.emit(&#039;message&#039;, message);\n    appendMessage(&#039;You&#039;, message); \/\/ Display the sent message immediately\n    messageInput.value = &#039;&#039;; \/\/ Clear the input field\n  }\n});\n\n\/\/ Handle a new user joining\nsocket.on(&#039;user joined&#039;, (username) =&gt; {\n  appendMessage(&#039;System&#039;, `${username} joined the collaboration`);\n});\n\n\/\/ Handle receiving messages\nsocket.on(&#039;message&#039;, (data) =&gt; {\n  appendMessage(&#039;User&#039;, data); \/\/ Assuming all received messages are from a user named &#039;User&#039;\n});\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Extend your <code>index.js<\/code> file to handle WebSocket connections:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\n\/\/ index.js\n\nconst express = require(&#039;express&#039;);\nconst http = require(&#039;http&#039;);\nconst socketIO = require(&#039;socket.io&#039;);\n\nconst app = express();\nconst server = http.createServer(app);\nconst io = socketIO(server);\n\napp.use(express.static(&#039;public&#039;)); \/\/ Serve static files from the &#039;public&#039; directory\n\napp.get(&#039;\/&#039;, (req, res) =&gt; {\n  res.sendFile(__dirname + &#039;\/index.html&#039;);\n});\n\nconst users = new Map(); \/\/ Map to store connected users and their corresponding sockets\n\nio.on(&#039;connection&#039;, (socket) =&gt; {\n  console.log(&#039;A user connected&#039;);\n\n  \/\/ Prompt the user for their username\n  socket.emit(&#039;message&#039;, &#039;Please enter your username.&#039;);\n\n  \/\/ Handle setting and broadcasting usernames\n  socket.on(&#039;setUsername&#039;, (username) =&gt; {\n    users.set(socket.id, username);\n    socket.emit(&#039;message&#039;, `Welcome to the collaboration, ${username}!`);\n    socket.broadcast.emit(&#039;user joined&#039;, username);\n  });\n\n  \/\/ Handle messages from clients\n  socket.on(&#039;message&#039;, (data) =&gt; {\n    const username = users.get(socket.id) || &#039;Anonymous&#039;;\n    io.emit(&#039;message&#039;, `${username}: ${data}`);\n  });\n\n  \/\/ Handle disconnection\n  socket.on(&#039;disconnect&#039;, () =&gt; {\n    const username = users.get(socket.id) || &#039;Anonymous&#039;;\n    users.delete(socket.id);\n    io.emit(&#039;message&#039;, `${username} left the collaboration`);\n  });\n});\n\nconst PORT = process.env.PORT || 3000;\n\nserver.listen(PORT, () =&gt; {\n  console.log(`Server is running on http:\/\/localhost:${PORT}`);\n});\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Step 4: Run Your Application<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Back in your terminal, run the following command to start your server:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nnode index.js\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Visit <code>http:\/\/localhost:3000<\/code> in your web browser to see your real time collaborative app in action.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We sincerely hope you enjoyed reading this post. Although this tutorial is minimal, you may make your application better by including features like file sharing, user authentication and cooperation exchange. There are countless ways to develop dynamic real time web tools with WebSockets. Have fun with coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The development of real time tools has increased among modern web professionals. WebSockets is a useful tool that enables real time communication between clients and servers, whether you are developing a communication image tool, a live chat application, or a collaborative document editor In this article we will walk you through a they use WebSockets [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":229,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[39],"tags":[10,40,41,42],"class_list":["post-226","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-how-to","tag-javascript","tag-nodejs","tag-websockets"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/posts\/226","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=226"}],"version-history":[{"count":10,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/posts\/226\/revisions"}],"predecessor-version":[{"id":241,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/posts\/226\/revisions\/241"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/media\/229"}],"wp:attachment":[{"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=226"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=226"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/davagordon.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=226"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}