<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jon Lachlan</title>
    <description>The latest articles on DEV Community by Jon Lachlan (@jonlachlan).</description>
    <link>https://dev.to/jonlachlan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1476421%2F8715aae2-bfef-4fde-9dd6-0ae672e85665.png</url>
      <title>DEV Community: Jon Lachlan</title>
      <link>https://dev.to/jonlachlan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jonlachlan"/>
    <language>en</language>
    <item>
      <title>Real-Time WebSocket Connections for Node.js with ws-low-level</title>
      <dc:creator>Jon Lachlan</dc:creator>
      <pubDate>Sun, 26 May 2024 14:42:18 +0000</pubDate>
      <link>https://dev.to/jonlachlan/real-time-websocket-connections-for-nodejs-with-ws-low-level-38cj</link>
      <guid>https://dev.to/jonlachlan/real-time-websocket-connections-for-nodejs-with-ws-low-level-38cj</guid>
      <description>&lt;p&gt;Achieving real-time connections is easy using WebSockets. Though you may opt for long polling to update a client statelessly, the ability to handle and manage a stateful WebSocket connection makes it possible to work in real-time communications with the client.&lt;/p&gt;

&lt;p&gt;WebSocket is a bi-directional data messaging protocol. The connection begins as an HTTP call, which initiates a handshake to work through the details of the connection. Once the connection is established, the client and server can send messages to each other. Messages are formatted as UTF-8 text or binary.&lt;/p&gt;

&lt;p&gt;With the Node 22 update, the WebSocket client is now available in Node, so you can build server-to-server WebSocket connections with Node.js as the client.&lt;/p&gt;

&lt;p&gt;Clearly WebSockets have a lot of value, so let's build a server!&lt;/p&gt;

&lt;h2&gt;
  
  
  Achieving Real-Time Connections with Node.js
&lt;/h2&gt;

&lt;p&gt;In this article I'm going to show you how to get started with creating a WebSocket server for Node.js using the npm library ws-low-level. ws-low-level provides the API to receive and send messages, and handle the WebSocket handshake. &lt;/p&gt;

&lt;p&gt;As its name suggests, ws-low-level is &lt;em&gt;low-level&lt;/em&gt;, in the sense that it gives you access to the raw parts of the WebSocket protocol. With this access comes the trade-off of more control versus more verbosity. And ws-low-level is indeed verbose -- the example in the README file for the &lt;a href="https://www.npmjs.com/package/ws-low-level"&gt;ws-low-level repo&lt;/a&gt; is over 150 lines of code!&lt;/p&gt;

&lt;p&gt;That is not to say ws-low-level is overly complex, however. The example from the README file is simple enough. &lt;/p&gt;

&lt;p&gt;And the ws-low-level API is actually providing you with a robust, Promise-based, standard-compliant WebSocket server. Because it is low-level, you will have the opportunity, once your server is in development, to add to it and customize it the way that you want.&lt;/p&gt;

&lt;h3&gt;
  
  
  Getting Started
&lt;/h3&gt;

&lt;p&gt;I will walk you through setting up a WebSocket server using ws-low-level. &lt;/p&gt;

&lt;p&gt;First, make sure you have the correct prerequisites installed. You will need Node.js, which you can get from the &lt;a href="https://nodejs.org/en/download"&gt;Node download page&lt;/a&gt;. This will also install npm. You can check your installation by running &lt;code&gt;node --version&lt;/code&gt; and &lt;code&gt;npm --version&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let me explain how ws-low-level works with Node.js.&lt;/p&gt;

&lt;p&gt;ws-low-level ties in to the standard library of Node.js. In Node.js, the WebSocket HTTP upgrade is available through Node's &lt;code&gt;http&lt;/code&gt; package with the &lt;code&gt;'upgrade'&lt;/code&gt; event handler. A request to establish a WebSocket will trigger this event. Below is an example server that uses the event and logs the word "upgrade" to the console whenever a WebSocket connection is requested.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;http&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;http&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;httpServer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;http&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createServer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nx"&gt;request&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;http.IncomingMessage&amp;gt; */&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;http.ServerResponse&amp;gt; */&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// Handle HTTP messages by verbs like GET and POST&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;httpServer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;on&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;upgrade&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;request&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;http.IncomingMessage&amp;gt; */&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;socket&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;stream.Duplex&amp;gt; */&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;head&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;Buffer&amp;gt; websocket header */&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Handle a WebSocket connection&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;upgrade&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;httpServer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code shows how to use Node.js to handle a WebSocket. Note that Node.js does not handle the WebSocket handshake, nor parse incoming WebSocket frames, nor prepare outgoing messages as WebSocket frames. We need a third-party library to help get started with our WebSocket server. &lt;/p&gt;

&lt;h3&gt;
  
  
  Using ws-low-level
&lt;/h3&gt;

&lt;p&gt;Enter ws-low-level! ws-low-level is a third-party library available on npm for handling Node.js WebSocket connections. To install the library, enter in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;ws-low-level
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, back to our server, we can import from ws-low-level all of the imports that we will need. I recommend importing all five of the following imports, because you will eventually need them all.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;sendHandshake&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;getMessagesFactory&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;sendFactory&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;prepareWebsocketFrame&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;prepareCloseFramePayload&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;ws-low-level&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we can add a WebSocket handshake to the web server, and the connection will be established. Let's modify the callback for the &lt;code&gt;'upgrade'&lt;/code&gt; event to include &lt;code&gt;sendHandshake&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;httpServer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;on&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;upgrade&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;request&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;http.IncomingMessage&amp;gt; */&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;socket&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;stream.Duplex&amp;gt; */&lt;/span&gt; &lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;head&lt;/span&gt; &lt;span class="cm"&gt;/* &amp;lt;Buffer&amp;gt; websocket header */&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nf"&gt;sendHandshake&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="nx"&gt;socket&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code will complete the WebSocket handshake, establishing a WebSocket connection. (That was simple!)&lt;/p&gt;

&lt;h3&gt;
  
  
  Next Steps
&lt;/h3&gt;

&lt;p&gt;Now that we have a connection established, it should be clear what we need to do next -- we need to handle receiving and sending messages. To continue on your journey, I recommend you proceed to the example server on &lt;a href="https://www.npmjs.com/package/ws-low-level"&gt;ws-low-level's README&lt;/a&gt;. It should be clear how to use the send and receive functionalities.&lt;/p&gt;

&lt;p&gt;This has been a brief introduction to real-time WebSocket communication for Node.js using ws-low-level. As the creator of ws-low-level, I'd like to say thank you for reading!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
