{"id":1029,"date":"2021-02-04T18:56:49","date_gmt":"2021-02-04T18:56:49","guid":{"rendered":"https:\/\/codeinsightacademy.com\/blog\/?p=1029"},"modified":"2022-01-17T03:58:58","modified_gmt":"2022-01-17T03:58:58","slug":"web-socket-chat-app","status":"publish","type":"post","link":"https:\/\/codeinsightacademy.com\/blog\/javascript\/web-socket-chat-app\/","title":{"rendered":"web socket chat app"},"content":{"rendered":"\n<p><strong>chat_server.js<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst http = require('http');\nconst WebSocket = require('ws');\n\nconst port = 8989;\nconst server = http.createServer(express);\nconst wss = new WebSocket.Server({ server })\n\nwss.on('connection', function connection(ws) {\n  ws.on('message', function incoming(data) {\n    wss.clients.forEach(function each(client) {\n      if (client !== ws &amp;&amp; client.readyState === WebSocket.OPEN) {\n        client.send(data);\n      }\n    })\n  })\n})\n\nserver.listen(port, function() {\n  console.log(`Server is listening on ${port}!`)\n})\n\n<\/code><\/pre>\n\n\n\n<p><strong>index.html<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;center>&lt;h1>WS Chat App&lt;\/h1>&lt;\/center>\n&lt;pre id=\"messages\" style=\"height: 400px; overflow: scroll\">&lt;\/pre>\n&lt;input type=\"text\" id=\"messageBox\" placeholder=\"Type your message here\" style=\"display: block; width: 100%; margin-bottom: 10px; padding: 10px;\" onkeyup=\"validateInput(event)\"\/>\n&lt;button id=\"send\" title=\"Send Message!\" style=\"width: 100%; height: 30px;\">Send Message&lt;\/button>\n\n&lt;script>\n  (function() {\n    const sendBtn = document.querySelector('#send');\n    const messages = document.querySelector('#messages');\n    const messageBox = document.querySelector('#messageBox');\n\n    let ws;\n\n    function showMessage(message) {\n      if (message instanceof Blob) {\n        reader = new FileReader();\n\n        reader.onload = () => {\n        \/\/   console.log(\"Result: \" + reader.result);\n          messages.textContent += `\\n\\n${reader.result}`;\n        };\n\n        reader.readAsText(message);\n      } else {\n        console.log(\"Result: \" + message);\n        messages.textContent += `\\n\\n${message}`;\n      }\n\n      messages.scrollTop = messages.scrollHeight;\n      messageBox.value = \"\";\n    }\n\n    function init() {\n      if (ws) {\n        ws.onerror = ws.onopen = ws.onclose = null;\n        ws.close();\n      }\n\n      ws = new WebSocket('ws:\/\/localhost:8989');\n      ws.onopen = () => {\n        console.log('Connection opened!');\n      }\n      ws.onmessage = ({ data }) => showMessage(data);\n      ws.onclose = function() {\n        ws = null;\n      }\n    }\n\n\t\n    sendBtn.onclick = function() {\n      if (!ws) {\n        showMessage(\"No WebSocket connection :(\");\n        return ;\n      }\n\n      ws.send(messageBox.value);\n      showMessage(messageBox.value);\n    }\n\t\n\t\n\tmessageBox.onkeyup = function() {\n\t\tif(event.keyCode  == 13) {\n\t\t\tif (!ws) {\n\t\t\t\tshowMessage(\"No WebSocket connection :(\");\n\t\t\t\treturn ;\n\t\t\t}\n\n\t\t\tws.send(messageBox.value);\n\t\t\tshowMessage(messageBox.value);\n\t\t}\n    }\n\n    init();\n  })();\n&lt;\/script>\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>chat_server.js index.html<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[18],"tags":[],"_links":{"self":[{"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/posts\/1029"}],"collection":[{"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/comments?post=1029"}],"version-history":[{"count":3,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/posts\/1029\/revisions"}],"predecessor-version":[{"id":2118,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/posts\/1029\/revisions\/2118"}],"wp:attachment":[{"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/media?parent=1029"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/categories?post=1029"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeinsightacademy.com\/blog\/wp-json\/wp\/v2\/tags?post=1029"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}