{"id":7560,"date":"2022-12-29T16:40:55","date_gmt":"2022-12-29T11:10:55","guid":{"rendered":"https:\/\/innovationm.co\/?p=7560"},"modified":"2022-12-29T16:40:55","modified_gmt":"2022-12-29T11:10:55","slug":"websocket-beginner-guide","status":"publish","type":"post","link":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/","title":{"rendered":"Websocket beginner guide"},"content":{"rendered":"<p><strong> What is WebSocket?<\/strong><\/p>\n<p><span style=\"font-weight: 400;\"> WebSocket provides a way to exchange data between the browser and server via a persistent connection. The data can be passed in both directions as \u201cpackets\u201d, without breaking the connection and the need for additional HTTP requests.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><strong> Where can we use WebSocket?<\/strong><\/p>\n<p><span style=\"font-weight: 400;\"> we use WebSocket where we need real-time data sharing i.e. online trading platforms, games, and social media platforms.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><strong>Frontend Example &#8211;<\/strong><\/p>\n<p><span style=\"font-weight: 400;\">To open a WebSocket connection we need to create a new protocol.<\/span><\/p>\n<p><em><span style=\"font-weight: 400;\">let socket = new WebSocket(&#8220;ws:\/\/localhost:3000&#8221;);<\/span><\/em><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">Once the socket is created, we should listen to events on it. There are totally 4 events:<\/span><\/p>\n<pre><span style=\"font-weight: 400;\">open \u2013 connection established,<\/span>\r\n\r\n<span style=\"font-weight: 400;\">message \u2013 data received,<\/span>\r\n\r\n<span style=\"font-weight: 400;\">error \u2013 WebSocket error,<\/span>\r\n\r\n<span style=\"font-weight: 400;\">close \u2013 connection closed.<\/span><\/pre>\n<pre><span style=\"font-weight: 400;\">let socket = new WebSocket(\"ws:\/\/localhost.com\");<\/span>\r\n\r\n\r\n\r\n\r\n<span style=\"font-weight: 400;\">socket.onopen = function(e) {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0alert(\"[open] Connection established\");<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0alert(\"Sending to server\");<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0socket.send(\"My name is tejendra\");<\/span>\r\n\r\n<span style=\"font-weight: 400;\">};<\/span><\/pre>\n<pre>\r\n\r\n\r\n<span style=\"font-weight: 400;\">socket.onmessage = function(event) {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0alert(`[message] Data received from server: ${event.data}`);<\/span>\r\n\r\n<span style=\"font-weight: 400;\">};<\/span>\r\n\r\n\r\n\r\n\r\n<span style=\"font-weight: 400;\">socket.onclose = function(event) {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0if (event.wasClean) {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0\u00a0\u00a0alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0} else {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0\u00a0\u00a0alert('[close] Connection died');<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0}<\/span>\r\n\r\n<span style=\"font-weight: 400;\">};<\/span><\/pre>\n<p>&nbsp;<\/p>\n<pre><span style=\"font-weight: 400;\">socket.onerror = function(error) {<\/span>\r\n\r\n<span style=\"font-weight: 400;\">\u00a0\u00a0alert(`[error] ${error.message}`);<\/span>\r\n\r\n<span style=\"font-weight: 400;\">};<\/span><\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">We need to have a server database for the above demo too, so we can connect to the server.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">So you\u2019ll see events open \u2192 message \u2192 close. and if there is an error then onerror in the end.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">When a new WebSocket (URL) is created, it starts connecting immediately.<\/span><\/p>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">During the connection, the browser (using headers) asks the server: \u201cDo you support Websocket? \u201dAnd if the server replies \u201cyes\u201d, then the talk continues in WebSocket protocol.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">If you want to use it in the front end, the best way to use it is socket.io which works on both the client and server sides.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">There are some methods to use in socket.io<\/span><\/p>\n<pre><span style=\"font-weight: 400;\">\/\/connect to server<\/span>\r\n\r\n<span style=\"font-weight: 400;\">const socket = io(\"http:\/\/localhost.com\");<\/span>\r\n\r\n\r\n\r\n\r\n<span style=\"font-weight: 400;\">\/\/on() - listen to custom events or default events. (receive)<\/span>\r\n\r\n<span style=\"font-weight: 400;\">socket.on('connect', console.log('connect to server'))<\/span>\r\n\r\n\r\n\r\n\r\n<span style=\"font-weight: 400;\">\/\/emit() - sent custom or default event to server. (send)<\/span>\r\n\r\n<span style=\"font-weight: 400;\">socket.emit('custom-event', 10, 'Hi', 'send')<\/span><\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">important &#8211; both server and client have the same event name to work.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">But how to send data from the server?<\/span><\/p>\n<p><span style=\"font-weight: 400;\">For that, we need to use the same methods on the server side too.<\/span><\/p>\n<pre><span style=\"font-weight: 400;\">\/\/broadcast.emit() - send custom or default event to everyone except the sender.<\/span>\r\n\r\n<span style=\"font-weight: 400;\">socket. broadcast. emit('custom event, 10, 'Hi', 'send')<\/span>\r\n\r\n\r\n\r\n\r\n<span style=\"font-weight: 400;\">\/\/to(room) - send a message to a specific room or group<\/span>\r\n\r\n<span style=\"font-weight: 400;\">socket. to(\"some room\").emit(\"some event\");<\/span><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>What is WebSocket? WebSocket provides a way to exchange data between the browser and server via a persistent connection. The data can be passed in both directions as \u201cpackets\u201d, without breaking the connection and the need for additional HTTP requests. &nbsp; Where can we use WebSocket? we use WebSocket where we need real-time data sharing [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7561,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[256,360],"tags":[722,224,259,820],"class_list":["post-7560","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-application","category-javascript","tag-blog","tag-java","tag-web","tag-websocket"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Websocket beginner guide - InnovationM - Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Websocket beginner guide - InnovationM - Blog\" \/>\n<meta property=\"og:description\" content=\"What is WebSocket? WebSocket provides a way to exchange data between the browser and server via a persistent connection. The data can be passed in both directions as \u201cpackets\u201d, without breaking the connection and the need for additional HTTP requests. &nbsp; Where can we use WebSocket? we use WebSocket where we need real-time data sharing [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"InnovationM - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-12-29T11:10:55+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1689\" \/>\n\t<meta property=\"og:image:height\" content=\"950\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"InnovationM Admin\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"InnovationM Admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/\"},\"author\":{\"name\":\"InnovationM Admin\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\"},\"headline\":\"Websocket beginner guide\",\"datePublished\":\"2022-12-29T11:10:55+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/\"},\"wordCount\":259,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Websocket-Beginner-Guide.png\",\"keywords\":[\"blog\",\"java\",\"Web\",\"websocket\"],\"articleSection\":[\"Java Application\",\"JavaScript\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/\",\"name\":\"Websocket beginner guide - InnovationM - Blog\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Websocket-Beginner-Guide.png\",\"datePublished\":\"2022-12-29T11:10:55+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Websocket-Beginner-Guide.png\",\"contentUrl\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/wp-content\\\/uploads\\\/2022\\\/12\\\/Websocket-Beginner-Guide.png\",\"width\":1689,\"height\":950},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/websocket-beginner-guide\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Websocket beginner guide\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/\",\"name\":\"InnovationM - Blog\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/#\\\/schema\\\/person\\\/a831bf4602d69d1fa452e3de0c8862ed\",\"name\":\"InnovationM Admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g\",\"caption\":\"InnovationM Admin\"},\"sameAs\":[\"http:\\\/\\\/www.innovationm.com\\\/\"],\"url\":\"https:\\\/\\\/www.innovationm.com\\\/blog\\\/author\\\/innovationmadmin\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Websocket beginner guide - InnovationM - Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/","og_locale":"en_US","og_type":"article","og_title":"Websocket beginner guide - InnovationM - Blog","og_description":"What is WebSocket? WebSocket provides a way to exchange data between the browser and server via a persistent connection. The data can be passed in both directions as \u201cpackets\u201d, without breaking the connection and the need for additional HTTP requests. &nbsp; Where can we use WebSocket? we use WebSocket where we need real-time data sharing [&hellip;]","og_url":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/","og_site_name":"InnovationM - Blog","article_published_time":"2022-12-29T11:10:55+00:00","og_image":[{"width":1689,"height":950,"url":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png","type":"image\/png"}],"author":"InnovationM Admin","twitter_misc":{"Written by":"InnovationM Admin","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#article","isPartOf":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/"},"author":{"name":"InnovationM Admin","@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed"},"headline":"Websocket beginner guide","datePublished":"2022-12-29T11:10:55+00:00","mainEntityOfPage":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/"},"wordCount":259,"commentCount":0,"image":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png","keywords":["blog","java","Web","websocket"],"articleSection":["Java Application","JavaScript"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/","url":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/","name":"Websocket beginner guide - InnovationM - Blog","isPartOf":{"@id":"https:\/\/www.innovationm.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#primaryimage"},"image":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#primaryimage"},"thumbnailUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png","datePublished":"2022-12-29T11:10:55+00:00","author":{"@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed"},"breadcrumb":{"@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#primaryimage","url":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png","contentUrl":"https:\/\/www.innovationm.com\/blog\/wp-content\/uploads\/2022\/12\/Websocket-Beginner-Guide.png","width":1689,"height":950},{"@type":"BreadcrumbList","@id":"https:\/\/www.innovationm.com\/blog\/websocket-beginner-guide\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.innovationm.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Websocket beginner guide"}]},{"@type":"WebSite","@id":"https:\/\/www.innovationm.com\/blog\/#website","url":"https:\/\/www.innovationm.com\/blog\/","name":"InnovationM - Blog","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.innovationm.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.innovationm.com\/blog\/#\/schema\/person\/a831bf4602d69d1fa452e3de0c8862ed","name":"InnovationM Admin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/5c99d9eece9dfbc82297cf34ddd58e9fe05bb52fe66c8f6bf6c0a45bfb6d7629?s=96&r=g","caption":"InnovationM Admin"},"sameAs":["http:\/\/www.innovationm.com\/"],"url":"https:\/\/www.innovationm.com\/blog\/author\/innovationmadmin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts\/7560","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/comments?post=7560"}],"version-history":[{"count":0,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/posts\/7560\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/media\/7561"}],"wp:attachment":[{"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/media?parent=7560"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/categories?post=7560"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.innovationm.com\/blog\/wp-json\/wp\/v2\/tags?post=7560"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}