{"id":537,"date":"2020-04-12T12:30:06","date_gmt":"2020-04-12T16:30:06","guid":{"rendered":"https:\/\/itp.nyu.edu\/networks\/?page_id=537"},"modified":"2020-05-21T10:24:39","modified_gmt":"2020-05-21T14:24:39","slug":"an-introduction-to-websocket","status":"publish","type":"page","link":"https:\/\/itp.nyu.edu\/networks\/an-introduction-to-websocket\/","title":{"rendered":"An Introduction to WebSocket"},"content":{"rendered":"<h2><span class=\"ez-toc-section\" id=\"Introduction\"><\/span>Introduction<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>From time to time, you might run into a situation where you want to build a web project that requires continuous communication between multiple parties on the web &#8211; for instance, a chat room, a multi-player shooter game, or even, a live performance. These are cases where WebSockets may be useful.\u00a0 This page introduces WebSockets,\u00a0 a technology that allows you to build\u00a0continuous communications between a web client and a server for this purpose, along with a few hands-on examples to try out.<\/p>\n<p>To get the most out of these notes,To get the most out of these notes, you should know\u00a0<a href=\"https:\/\/itp.nyu.edu\/networks\/explanations\/a-gentle-introduction-to-http\/\">what HTTP is<\/a>\u00a0and how HTTP requests work, and have a basic understanding of <a href=\"https:\/\/www.geeksforgeeks.org\/client-server-model\/\">how the client-server model works on the web<\/a>.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"What_are_WebSockets\"><\/span>What are WebSockets?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The usual way that a web client communicates with a server is done by sending requests and getting responses back from the server using the <strong>Hypertext Transport Protocol, HTTP<\/strong>. A client sends a request to a server asking for some information, and the server makes a response to that client with the corresponding information.<\/p>\n<p>Normally a web request does not include a continuous connection &#8212; a request is sent, then the connection closes. This has made continuous communication a bit difficult and tedious, since the client will need to reconnect every time they want to send or receive a message. It&#8217;s also limited by the fact that the server doesn&#8217;t initiate communication, it only waits for the client to make a request.<\/p>\n<p>There are some exceptions to this, such as AJAX and Long-Polling. <strong>AJAX<\/strong>, or <strong>Aysnchronous JavaScript and XML<\/strong>, is a technique for dynamically altering an HTML page after the page has been requested and loaded and without leaving the page. In AJAX, a script that loads with the HTML page makes continued requests to the server, and modifies the HTML page after its initial load.\u00a0 <strong>Long-Polling<\/strong> is a technique where a client\u00a0 makes a request to a server and leaves the request open so that the server can continue to send new information to the client. However, since\u00a0both of these methods are built around the\u00a0request\/response paradigm of HTTP, they&#8217;re not well suited for low latency applications.<\/p>\n<p>To address this issue,\u00a0the W3C, the body responsible for web standards,\u00a0 introduced\u00a0the <strong>WebSocket<\/strong> &#8212; a computer communications protocol providing full-duplex communication channels over a single TCP connection. [<a href=\"#footnote-1\">1<\/a>] Using this protocol, a web client can establish a persistent connection between the client and the server &#8212; called a socket &#8212; so that both parties can send data at any time, as long as the socket is open. [<a href=\"#footnote-2\">2<\/a>]<\/p>\n<p>WebSockets allow a server to initiate dialogue from its side, requesting information from or pushing information to the client whenever needed.\u00a0 If multiple clients connect simultaneously, the server can also broadcast information to all currently connected clients and pass along messages sent from one client to another. WebSockets still require the client to initiate contact with the server, but once the socket is established, communication can move in both directions.<\/p>\n<p>Websockets are also\u00a0cross-platform [<a href=\"#footnote-3\">3<\/a>], <a href=\"https:\/\/itp.nyu.edu\/networks\/an-introduction-to-cross-origin-resource-sharing-cors\/\">cross-origin<\/a> by nature[<a href=\"#footnote-4\">4<\/a>], and they can<strong>\u00a0<\/strong>traverse firewalls and proxies\u00a0[<a href=\"#footnote-5\">5<\/a>].<\/p>\n<h2><span class=\"ez-toc-section\" id=\"How_do_WebSockets_Work_%E2%80%93_The_WebSocket_Protocol\"><\/span>How do WebSockets Work &#8211;\u00a0The WebSocket Protocol<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>If you just want to use WebSocket, you can skip this section and go to the example below that shows you how to establish a WebSocket connection. If you&#8217;re interested in what&#8217;s behind the scene,\u00a0this is what happens:<\/p>\n<p>A<strong>\u00a0<\/strong>WebSocket\u00a0is a thin wrapper around a normal TCP socket.\u00a0 Figure 1, from <a href=\"https:\/\/javascript.info\/websocket\">javascript.info<\/a>\u00a0[<a href=\"#footnote-6\">6<\/a>] illustrates how WebSocket works.<\/p>\n<figure style=\"width: 429px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/javascript.info\/article\/websocket\/websocket-handshake.svg\" alt=\"websocket-handshake\" width=\"429\" height=\"348\" \/><figcaption class=\"wp-caption-text\">Figure 1. This figure illustrates how WebSocket works at a high level. A client (in this case a Web Browser) sends an HTTP request to the server, asking &#8220;Hey, server, let&#8217;s establish a WebSocket?&#8221;. The server answers with an HTTP response saying &#8220;Okay!&#8221; and encrypts the connection. Then the two parties begin talking in WebSocket protocol.<\/figcaption><\/figure>\n<p>After the initial handshake is done via HTTP, the communication then continues using the same TCP connection using WebSocket protocol. The TCP connection will be closed once both parties acknowledge that the WebSocket connection should be closed. WebSockets are encrypted using a public key generated by the client when the socket request is made.<\/p>\n<p>Now let&#8217;s take a look at how WebSocket works in a bit more detail, referencing the Echo Test example on\u00a0<a href=\"https:\/\/www.websocket.org\/echo.html\">websocket.org<\/a>. In this example, you have a WebSocket client in your browser, and you want to connect it to a WebSocket server hosted on echo.websocket.org, which echoes whatever messages sent to it.<\/p>\n<p>To establish a WebSocket connection, your client will need to send a request to a URI using the WebSocket scheme &#8211; a URI that begins with <em>ws:\/\/<\/em>\u00a0(or <em>wss:\/\/<\/em>\u00a0for a secure WebSocket). The remainder of the URI would be the same as an <a href=\"http:\/\/www.ltg.ed.ac.uk\/~ht\/WhatAreURIs\/\">HTTP URI<\/a>. In this case, your requesting URI would be <em>wss:\/\/echo.websocket.org.<\/em><\/p>\n<p>Then the client will send an HTTP GET request to the specified URI as a WebSocket opening handshake with the following required headers:<\/p>\n<ul>\n<li>\n<pre>Connection: Upgrade<\/pre>\n<p>\u00a0\u2013 signal that we want to keep the connection alive, and use it for non-HTTP requests.<\/li>\n<li>\n<pre>Upgrade: websocket<\/pre>\n<p>\u00a0\u2013 signal that the client wants to establish a WebSocket connection.<\/li>\n<li>\n<pre>Sec-WebSocket-Key<\/pre>\n<p>\u00a0\u2013 a random browser-generated key for security.<\/li>\n<li>\n<pre>Sec-WebSocket-Version<\/pre>\n<p>\u00a0\u2013 WebSocket protocol version.<\/li>\n<\/ul>\n<p>A complete list of HTTP headers that your client send might look something like this:<\/p>\n<pre class=\"line-numbers language-none\">\r\nGET wss:\/\/echo.websocket.org HTTP\/1.1\r\nHost: echo.websocket.org\r\nOrigin: https:\/\/localhost\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: Iv8io\/9s+lYFgZWcXczP8Q==\r\nSec-WebSocket-Version: 13<\/pre>\n<p>If the server agrees to switch to WebSocket, it should send code 101 response:<\/p>\n<pre class=\"line-numbers language-none\">\r\nHTTP\/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: hsBlbuDTkk24srzEOTBUlZAlC2g=<\/pre>\n<p>After the client receives the server response, the HTTP connection\u00a0is replaced by the WebSocket connection over the same underlying TCP\/IP connection. You can learn more about how data is transmitted and the subprotocols in The WebSocket Protocol section of this\u00a0<a href=\"https:\/\/sookocheff.com\/post\/networking\/how-do-websockets-work\/\">How Do Websockets Work? <\/a>article.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"How_To_Create_a_WebSocket_Client_in_the_Browser\"><\/span>How To Create a WebSocket Client in the Browser<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Let&#8217;s create a simple WebSocket client in the browser that talks to an echo server on websocket.org using plain JavaScript. This example assumes that you have some basic knowledge of <a href=\"https:\/\/github.com\/ITPNYU\/ICM-2019-Code\/blob\/master\/weeks\/07_dom.md\">how HTML &amp; JavaScript works<\/a>.<\/p>\n<p>You can download the example code from this repository:<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/ITPNYU\/NetworksSite\/tree\/master\/Intro-to-WebSocket\">An Introduction to WebSocket<\/a><\/li>\n<\/ul>\n<p>Open the websocket-client.html file in your browser, then open the JavaScript console (or the developer tool in your browser). You should be able to see something like Figure 2:<\/p>\n<figure style=\"width: 622px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\" wp-image-627 aligncenter\" src=\"https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/1-websocket-client-html.png\" alt=\"An HTML page showing a simple websocket client\" width=\"622\" height=\"177\" srcset=\"https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/1-websocket-client-html.png 1212w, https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/1-websocket-client-html-300x85.png 300w, https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/1-websocket-client-html-768x219.png 768w, https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/1-websocket-client-html-1024x291.png 1024w\" sizes=\"(max-width: 622px) 85vw, 622px\" \/><figcaption class=\"wp-caption-text\">Figure 2. This image shows the console logs of the simple WebSocket client example, which include: &#8220;CONNECTED To wss:\/\/echo.websocket.org&#8221;, &#8220;SENT: Hello server!&#8221;, &#8220;RESPONSE: Hello server!&#8221;, and &#8220;DISCONNECTED&#8221;.<\/figcaption><\/figure>\n<p>This is a simple HTML file that does the following:<\/p>\n<ol>\n<li>Create a WebSocket client<\/li>\n<li>Connect the client to a WebSocket server hosted on wss:\/\/echo.websocket.org<\/li>\n<li>Send a message &#8220;Hello server!&#8221;<\/li>\n<li>Get an echo response from the server<\/li>\n<li>Disconnect the client from the server<\/li>\n<\/ol>\n<p>Now let&#8217;s open the HTML file with a plain text editor like VS Code or Atom and see how it actually works:<\/p>\n<pre>\r\n\/\/create a websocket client and define event handlers\r\nfunction init() {\r\n   myWebsocket = new WebSocket(wsUri); \/\/create a websocket client that connects to a target URI\r\n   myWebsocket.onopen = openSocket;\r\n   myWebsocket.onclose = closeSocket;\r\n   myWebsocket.onmessage = handleMassage;\r\n   myWebsocket.onerror = handleError;\r\n}\r\n<\/pre>\n<p>At the top, you&#8217;ll see an init() function that will be run when the HTML page finishes loading. This function will create a WebSocket client. By using the syntax <em>new WebSocket(wsUri),\u00a0<\/em>a WebSocket client instance called &#8220;<em>myWebsocket<\/em>&#8221; is created in your browser, and it&#8217;ll attempt to connect to any URI string provided (in this case, it is <em>&#8220;wss:\/\/echo.websocket.org\/&#8221;<\/em>)<em>.<\/em><\/p>\n<p>There are typically four <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Learn\/JavaScript\/Building_blocks\/Events\">event handlers<\/a> that come with the WebSocket API and will be useful for us:<\/p>\n<ul>\n<li><em>onopen<\/em>, a function that is called when\u00a0the connection is ready to send and receive data<\/li>\n<li><em>onclose<\/em>, a function that is called when the WebSocket connection&#8217;s readyState changes to CLOSED<\/li>\n<li><em>onmessage<\/em>,\u00a0a function that is called when a message is received from the server<\/li>\n<li><em>onerror<\/em>,\u00a0a function that is called when\u00a0an error occurs on the WebSocket<\/li>\n<\/ul>\n<p>You can define how to respond to each of these events by creating your own event handler functions. We&#8217;ll take a look at the two most important ones, <em>onopen<\/em> and <em>onmessage<\/em>.<\/p>\n<pre>  \r\n\/\/print connection status to console, and send a message to the server\r\nfunction openSocket(evt) {\r\n   console.log(\"CONNECTED To \" + wsUri);\r\n   doSend(\"Hello server!\");\r\n}\r\n<\/pre>\n<p>First, we assign a handler function called <em>openSocket<\/em> to <em>onopen <\/em>by <em>myWebsocket<\/em><em>.onopen = openSocket<\/em>. By doing so, when the connection is successful and ready, the browser will call the <em>openSocket<\/em> function, and it&#8217;ll do two things: 1) print connection status to console, and 2) send a message to the server by calling the <em>doSend()<\/em> function.<\/p>\n<pre>\r\n\/\/send a message to server, and print sent message to console\r\nfunction doSend(message) {\r\n   myWebsocket.send(message);\r\n   console.log(\"SENT: \" + message);\r\n}\r\n<\/pre>\n<p><em>doSend()\u00a0<\/em>is a function that: uses the <em>&#8220;myWebsocket&#8221;<\/em>\u00a0client to\u00a0send a message to the server by using the WebSocket API&#8217;s\u00a0<em>.send()<\/em> method,. It also prefixes the message with &#8220;SENT: &#8221; and prints it to console. In this case, it&#8217;ll send &#8220;Hello server!&#8221; to the server and print &#8220;SENT: Hello server!&#8221; to the console.<\/p>\n<p>The\u00a0<em>handleMessage()\u00a0<\/em>function, on the other hand, will be called whenever the client receives a message from the server.\u00a0Since the server is an echo server, our client will receive the same message it sends out, &#8220;Hello server!&#8221;.<\/p>\n<pre>\r\n\/\/print response message from server to console, and close the connection\r\nfunction handleMassage(evt) {\r\n   console.log('RESPONSE: ' + evt.data);\r\n   myWebsocket.close();\r\n}\r\n<\/pre>\n<p>When <em>handleMessage()\u00a0<\/em>is called, it comes with a message event object that contains the received message. In this case, we get the event in a variable called\u00a0<em>evt<\/em>, then we can access the message via <em>evt.data<\/em>. Then\u00a0we ask the browser to do two things: first, print the message to the console, and second, close the WebSocket connection by calling <em>myWebsocket.close()<\/em>.<\/p>\n<pre>\r\n\/\/print disconnected message to console\r\nfunction closeSocket(evt) {\r\n   console.log(\"DISCONNECTED\");\r\n}\r\n<\/pre>\n<p>Once the connection is closed, the\u00a0<em>closeSocket()<\/em> function will be called. It will print the message &#8220;DISCONNECTED&#8221; to the console.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Creating_WebSocket_Clients_and_Servers_With_wsjs_and_SocketIO\"><\/span>Creating WebSocket Clients and Servers With\u00a0ws.js and Socket.IO<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>There are different JavaScript libraries for creating WebSocket Clients and servers. The two most popular are ws.js, and Socket.io. Each has its own strengths and weaknesses., and each has different ways to implement a WebSocket client and server and determine how messages are communicated between server and client. In this section, you&#8217;ll see client and server examples using ws.js and Socket.io.<\/p>\n<p>To use these examples, you&#8217;ll need to have <a href=\"https:\/\/nodejs.org\/en\/\">Node.js<\/a> installed in your computer, and have some basic knowledge of using the Terminal (on MAC\/Linux) or the Command tool (on Windows). Node.js is a JavaScript runtime environment that executes JavaScript code outside of a web browser on personal computers and servers. You can learn more about Node.js in <a href=\"https:\/\/itp.nyu.edu\/physcomp\/labs\/labs-serial-communication\/lab-serial-communication-with-node-js\/\">the Node.js section of this tutorial<\/a>.<\/p>\n<p>Once you have Node.js installed, you can download and use the examples\u00a0in this repository:<\/p>\n<ul>\n<li><strong><a href=\"https:\/\/github.com\/ITPNYU\/NetworksSite\/tree\/master\/Intro-to-WebSocket\">An Introduction to WebSocket<\/a><\/strong><\/li>\n<\/ul>\n<h3><span class=\"ez-toc-section\" id=\"wsjs\"><\/span>ws.js<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><a href=\"https:\/\/www.npmjs.com\/package\/ws\">ws.js<\/a> is a\u00a0simple-to-use WebSocket server implementation on Node.js. It is very lightweight. ws.js uses the native WebSocket object in the browser to create a client, as you saw in the example above.\u00a0 Here we use ws.js to create an echo server in node.js, and reuse the client example above to connect to the server.<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Server_Example\"><\/span>Server Example:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Open terminal, cd to the ws folder, and install the ws library dependency by entering:<\/p>\n<pre class=\" language-javascript\">npm install<\/pre>\n<p>Run the server by typing the following command:<\/p>\n<pre class=\"language-javascript\">node server.js<\/pre>\n<p>You should see a message saying &#8220;WebSocket server listening on port:8081&#8221; in your terminal. It means that the echo WebSocket server is up and running on port 8081 of your local computer, and ready to be connected by a client.<\/p>\n<p>Open the server.js file in a plain text editor to check to code.<\/p>\n<pre class=\"language-javascript\">\r\nconst WebSocket = require('ws'); \/\/ Include the ws.js module.\r\nlet myPort = 8081;\r\nconst wss = new WebSocket.Server({ port: myPort }); \/\/create a WebSocket server\r\n\r\nconsole.log(\"WebSocket server listening on port:\" + myPort);\r\n\r\n\/\/whenever a client connects to the server, the handleConnection function will be called:\r\nwss.on('connection', handleConnection);\r\n\r\nfunction handleConnection(ws) {\r\n   \/\/when a message from the client is received, the\u00a0handleMessage\u00a0function will be called:\r\n   ws.on('message', handleMessage);\r\n\r\n   function handleMessage(message) {\r\n      console.log('received: %s', message);\r\n      \/\/send the message back to the client:\r\n      ws.send(message);\r\n   }\r\n}\r\n<\/pre>\n<p>Here&#8217;s how the script works:<\/p>\n<ol>\n<li>Include the ws.js module by calling <em>require(&#8216;ws&#8217;).<\/em><\/li>\n<li>Use it to create a WebSocket server via <em>new WebSocket.Server({ port:[your port number]}).<\/em><\/li>\n<li>Define an event handler function <em>handleConnection<\/em> for the <em>connection<\/em> event of the server by <em>wss.on(&#8216;connection&#8217;, handleConnection)<\/em>. This means whenever a client connects to the server, the <em>handleConnection<\/em> function will be called.<\/li>\n<li>A socket object, <em>ws<\/em>, will be passed to the\u00a0<em>handleConnection<\/em> function. We can then define an event handler function\u00a0<em>handMessage<\/em> for its\u00a0<em>message\u00a0<\/em>event by <em>ws.on(&#8216;message&#8217;, handleMessage)<\/em>. In this case,\u00a0when a message from the client is received, the\u00a0<em>handleMessage\u00a0<\/em>function will be called.<\/li>\n<li>Finally, define what should be to the received message. Here, we&#8217;ll bounce the message back to the client using the <em>.send()<\/em> method, hence <em>ws.send(message)<\/em>.<\/li>\n<\/ol>\n<h4><span class=\"ez-toc-section\" id=\"Client_Example\"><\/span>Client Example:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>With the server up and running, open the client.html file in your browser and then open console. You should see something like Figure 3:<\/p>\n<figure style=\"width: 630px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-632 aligncenter\" src=\"https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/2-wsjs-client-html.png\" alt=\"wsjs client html page\" width=\"630\" height=\"128\" srcset=\"https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/2-wsjs-client-html.png 1218w, https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/2-wsjs-client-html-300x62.png 300w, https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/2-wsjs-client-html-1024x210.png 1024w\" sizes=\"(max-width: 630px) 85vw, 630px\" \/><figcaption class=\"wp-caption-text\">Figure 3. This image shows the console logs of the ws.js WebSocket client example, which include: &#8220;CONNECTED To ws:\/\/localhost:8081&#8221;, &#8220;SENT: Hello server!&#8221;, &#8220;RESPONSE: Hello server!&#8221;, and &#8220;DISCONNECTED&#8221;.<\/figcaption><\/figure>\n<p>The client code is basically the same as the client code in the above section. The only difference is that instead of connecting to an echo server on echo.websocket.org, it is now connecting to the echo server running on our local computer with the URI <em>&#8220;ws:\/\/localhost:8081&#8221;<\/em>.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"SocketIO\"><\/span>Socket.IO<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><a href=\"https:\/\/www.npmjs.com\/package\/socket.io\">Socket.IO<\/a> is a library that\u00a0simplifies\u00a0the usage of WebSockets in more advanced situations like sending a message from server to reach on all clients, and\u00a0it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. However, it comes with some overhead and it also requires a separate library on the client, as opposed to the example you saw in the previous section.\u00a0[<a href=\"#footnote-7\">7<\/a>]<\/p>\n<h4><span class=\"ez-toc-section\" id=\"Server_Example-2\"><\/span>Server Example:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>1. Open terminal, cd to the socketio folder, and install the library dependency:<\/p>\n<pre class=\" language-javascript\">npm install<\/pre>\n<p>2. Run the server by entering:<\/p>\n<pre class=\" language-javascript\">node server.js<\/pre>\n<p>3. You should see a message saying &#8220;Socket.IO listening on port:8081&#8221; in your terminal. It means that the echo SocketIO server is up and running on port 8081 of your local computer, and readyim to be connected by a client.<\/p>\n<p>4. You can open server.js in a plain text editor to check to code.<\/p>\n<pre>\r\nconst server = require('http').createServer();\r\nconst io = require('socket.io')(server); \/\/Attaches Socket.IO to a plain Node.JS HTTP server\r\nlet myPort = 8081;\r\n\r\nio.on('connection', handleConnection); \/\/define a handler for a connection event with a client.\r\n\r\nfunction handleConnection(socket) {\r\n   socket.emit('welcome'); \/\/emit()\u00a0means you're sending out an event.\r\n\r\n   socket.on('client message', handleClientMessage); \/\/attach handleClientMessage to a 'client message' event\r\n   socket.on('end', handleEnd); \/\/attach handleEnd an 'end' event\r\n\r\n   function handleClientMessage(message) {\r\n      console.log('received: %s', message);\r\n      socket.emit('server message', message); \/\/you can attach additional data in your emitted event by using\r\n      \/\/any number of additional parameters in\u00a0.emit(), like\u00a0.emit('ABC event', data1, ...).\r\n   };\r\n\r\n   function handleEnd() {\r\n      console.log('end connection');\r\n      socket.disconnect(0);\r\n   };\r\n}\r\n\r\nserver.listen(myPort); \/\/ask the HTTP server to listen on port 8081\r\nconsole.log(\"Socket.IO listening on port:\" + myPort);\r\n<\/pre>\n<p>What it does is:<\/p>\n<ol>\n<li>Attaches Socket.IO to a plain Node.JS HTTP server listening on port 8081.<\/li>\n<li>The <em>io.on(&#8216;connectoin&#8217;, &#8230;)<\/em> is similar to <em>wss.on(&#8216;connection&#8217;,\u00a0 &#8230;)<\/em>. It allows you to define a handler for a connection with a client. Here the handler is\u00a0<em>handleConnection<\/em>.<\/li>\n<li>As opposed to ws.js, where the name of the events are predetermined (e.g. &#8216;message&#8217;), you&#8217;re free to define your own events using the <em>.emit()<\/em> and <em>.on()\u00a0<\/em>pair.<\/li>\n<li><em>.emit()\u00a0<\/em>means you&#8217;re sending out an event. In this case, <em>socket.emit(&#8216;welcome&#8217;)<\/em> means you&#8217;re sending an event with a name called &#8216;welcome&#8217; to the connected client.<\/li>\n<li><em>.on()<\/em> means you&#8217;re listening to an event. Here the server is listening to two types of events, <em>&#8216;client message&#8217;\u00a0<\/em>and <em>&#8216;end&#8217;<\/em>. Respective handlers are defined: <em>handleClientMessage<\/em> will echo a &#8216;server message&#8217; event with whatever message it gets from the client, and\u00a0<em>handleEnd<\/em> will disconnect the client.<\/li>\n<li>One benefit of using Socket.IO is that the names of the events can be arbitrary, like <em>.emit(&#8216;ABC event&#8217;)<\/em>.\u00a0Also, you can attach additional data in your emitted event by using any number of additional parameters in\u00a0<em>.emit()<\/em>, like\u00a0<em>.emit(&#8216;ABC event&#8217;, data)<\/em>. The data can be strings, numbers, or objects.<\/li>\n<\/ol>\n<h4><span class=\"ez-toc-section\" id=\"Client_Example-2\"><\/span>Client Example:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n<p>Now open client.html in your browser and then open console. You should be able to see something like Figure 4:<\/p>\n<figure style=\"width: 630px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-638 aligncenter\" src=\"https:\/\/itp.nyu.edu\/networks\/wp-content\/uploads\/2020\/04\/3-socketio-client-html-new.png\" alt=\"socketio client html page\" width=\"630\" height=\"178\" \/><figcaption class=\"wp-caption-text\">Figure 4. This image shows the console logs of the Socket.IO WebSocket client example, which include: &#8220;CONNECTED To http:\/\/localhost:8081&#8221;, &#8220;SENT: Hello server!&#8221;, &#8220;RESPONSE: Hello server!&#8221;, and &#8220;DISCONNECTED&#8221;.<\/figcaption><\/figure>\n<p>Open the code with a plain text editor. The way of creating a client with Socket.IO is similar to a Socket.IO server. The differences are:<\/p>\n<pre>\r\n\/\/create a websocket client and define event handlers\r\nfunction init() {\r\n   myWebsocket = io(serverUri); \/\/connecting to the server\r\n   myWebsocket.on('welcome', handleWelcome);\r\n   myWebsocket.on('server message', handleServerMassage);\r\n   myWebsocket.on('disconnect', handleDisconnect); \/\/when the server calls socket.disconnect(0), the client will receive a 'disconnect' event.\r\n}<\/pre>\n<ol>\n<li>You need to include a client library via a script tag in your HTML file. Here we&#8217;re using the hosted Socekt.IO client js file via\n<div><em>&lt;script\u00a0src=&#8217;http:\/\/localhost:8081\/socket.io\/socket.io.js&#8217;&gt;&lt;\/script&gt;.\u00a0<\/em><\/div>\n<\/li>\n<li>We&#8217;re connecting to the server via <em>myWebsocket = io(serverUri)<\/em>.<\/li>\n<li>We&#8217;re defining the corresponding\u00a0sets of <em>.emit()\u00a0<\/em>and\u00a0<em>.on()<\/em> events based on the ones defined on the server side. Here we&#8217;re listening to the <em>&#8216;welcome&#8217;<\/em>, <em>&#8216;server message&#8217;<\/em>, and <em>&#8216;disconnect&#8217;<\/em> events emitted from the server, and attaching handlers for each of them.<\/li>\n<li>Note that when the server calls <em>socket.disconnect(0)<\/em>, the client will receive a &#8216;disconnect&#8217; event.<\/li>\n<li>The rest of the code follows a similar logic as the ws.js client.<\/li>\n<\/ol>\n<h2><span class=\"ez-toc-section\" id=\"Using_WebSockets_in_Arduino\"><\/span>Using WebSockets in Arduino<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You can also use WebSockets on an Arduino board. A typical use case is to create a WebSocket client and send messages (e.g. sensor data) to a server hosted somewhere else.<\/p>\n<p>The following example highlights how to create a WebSocket client on an Arduino board with WINC1500 module and send\/receive messages via WiFi. It assumes that you have some basic knowledge of <a href=\"https:\/\/itp.nyu.edu\/networks\/tutorials\/connecting-a-wifi-enabled-arduino-to-the-internet\/\">how to connect a WiFi-enabled Arduino to the Internet<\/a>.<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/tigoe\/MakingThingsTalk2\/blob\/master\/3rd_edition\/chapter5\/WebSocketClient\/WebSocketClient.ino\">Making Things Talk &#8211; Chapter 5 &#8211; WebSocket Client<\/a><\/li>\n<\/ul>\n<p>To create a client, you&#8217;ll need to include the SPI, WiFi101 (or WiFiNINA),\u00a0ArduinoHttpClient libraries, and provide SSID and password info via the config.h file. Then you&#8217;ll create a WebSocket client with a WiFiClient object, a server address, and a port.<\/p>\n<pre>\r\n#include \r\n\/\/#include &lt;WiFi101.h&gt; \/\/ use this for MKR1000 boards\r\n#include   &lt;WiFiNINA.h&gt; \/\/ use this for MKR1010 and Nano 33 IoT boards\r\n#include &lt;ArduinoHttpClient.h&gt;\r\n#include \"config.h\"     \/\/ includes char ssid[] and char pass[] for WiFi connect\r\n\r\nconst char serverAddress[] = \"192.168.0.22\"; \/\/ server address\r\nint port = 8080; \/\/ port number\r\nWiFiClient tcpSocket; \/\/ server socket\r\n\r\n\/\/ make a websocket instance\r\nWebSocketClient webSocket = WebSocketClient(tcpSocket, serverAddress, port);\r\n<\/pre>\n<p>To connect to a server, enter &#8220;c&#8221; via\u00a0Serial to connect to the server, and it&#8217;ll attempt to connect to the server by calling\u00a0<em>webSocket.<span class=\"pl-c1\">begin<\/span>()<\/em>\u00a0through the <em>connectToServer() <\/em>function. If the WebSocket is connected, you can send message via Serial by using <em>webSocket.beginMessage()<\/em>, <em>websocket.print()<\/em>, and <em>webSocket.endMessage().<\/em><\/p>\n<pre>\r\nif (Serial.available()) {\r\n   String input = Serial.readString();\r\n   if (input == \"c\") {\r\n      connectToServer();\r\n   } else if (input == \"x\") {\r\n      webSocket.stop();\r\n   } else {\r\n      if (webSocket.connected()) {              \/\/ and the webSocket's connected,\r\n         webSocket.beginMessage(TYPE_TEXT);   \/\/ message type: text\r\n         webSocket.print(input);\r\n         webSocket.endMessage();\r\n      }\r\n   }\r\n}\r\n\r\nvoid connectToServer() {\r\n   Serial.println(\"attempting to connect\");\r\n   boolean error = webSocket.begin();   \/\/ attempt to connect\r\n   if (error) {\r\n      Serial.println(\"failed to connect\");\r\n   } else {\r\n      Serial.println(\"connected\");\r\n   }\r\n}\r\n<\/pre>\n<p>To receive messages, you will use\u00a0<em>webSocket.<span class=\"pl-c1\">parseMessage<\/span>()<\/em>\u00a0and <em>webSocket.<span class=\"pl-c1\">readString<\/span>()<\/em>.<\/p>\n<pre>  \r\n\/\/ while websocket is connected, listen for incoming messages:\r\nif (webSocket.connected()) {\r\n   int msgLength = webSocket.parseMessage();  \/\/ get message length\r\n   if (msgLength &amp; gt; 0) {                       \/\/ if it's &gt; 0,\r\n      String message = webSocket.readString(); \/\/ read it\r\n      Serial.println(message);                 \/\/ print it\r\n   }\r\n}\r\n<\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Websockets are ways to do realtime communication between server and client within the context of HTTP. They can be done on any client device or software which implements the WebSocket protocol, like the ones we mentioned here. For further readings, see the references below.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"References\"><\/span>References<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<ol>\n<li><a href=\"https:\/\/en.wikipedia.org\/wiki\/WebSocket\" name=\"footnote-1\">WebSocket &#8211; Wikipedia<\/a><\/li>\n<li><a href=\"https:\/\/www.html5rocks.com\/en\/tutorials\/websockets\/basics\/\" name=\"footnote-2\">Introducing WebSockets: Bringing Sockets to the Web<\/a><\/li>\n<li><a href=\"https:\/\/itp.nyu.edu\/~sve204\/liveweb_fall2019\/week2.html#websockets\" name=\"footnote-3\">JAVASCRIPT 102 : BECOMING LIVE<\/a><\/li>\n<li><a href=\"https:\/\/javascript.info\/websocket\" name=\"footnote-4\">WebSocket<\/a><\/li>\n<li><a href=\"https:\/\/www.websocket.org\/aboutwebsocket.html\" name=\"footnote-5\">About HTML5 WebSocket<\/a><\/li>\n<li><a href=\"https:\/\/sookocheff.com\/post\/networking\/how-do-websockets-work\/\" name=\"footnote-6\">How Do Websockets Work?<\/a><\/li>\n<li><a href=\"https:\/\/stackoverflow.com\/questions\/10112178\/differences-between-socket-io-and-websockets\" name=\"footnote-7\">Differences between socket.io and websockets<\/a><\/li>\n<\/ol>\n<div id=\"gtx-trans\"><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Introduction From time to time, you might run into a situation where you want to build a web project that requires continuous communication between multiple parties on the web &#8211; for instance, a chat room, a multi-player shooter game, or even, a live performance. These are cases where WebSockets may be useful.\u00a0 This page introduces &hellip; <a href=\"https:\/\/itp.nyu.edu\/networks\/an-introduction-to-websocket\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;An Introduction to WebSocket&#8221;<\/span><\/a><\/p>\n","protected":false},"author":40,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-537","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/pages\/537"}],"collection":[{"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/comments?post=537"}],"version-history":[{"count":80,"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/pages\/537\/revisions"}],"predecessor-version":[{"id":726,"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/pages\/537\/revisions\/726"}],"wp:attachment":[{"href":"https:\/\/itp.nyu.edu\/networks\/wp-json\/wp\/v2\/media?parent=537"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}