<?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: Peter Carter</title>
    <description>The latest articles on DEV Community by Peter Carter (@someofthethings).</description>
    <link>https://dev.to/someofthethings</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%2F1057222%2Fe23817dd-4cfa-4534-b6da-c67d554c0519.JPG</url>
      <title>DEV Community: Peter Carter</title>
      <link>https://dev.to/someofthethings</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/someofthethings"/>
    <language>en</language>
    <item>
      <title>Create a websocket client/server setup with Angular, SocketIo and Ionic — Pt1, Node.js websocket server</title>
      <dc:creator>Peter Carter</dc:creator>
      <pubDate>Mon, 29 Jul 2024 13:58:45 +0000</pubDate>
      <link>https://dev.to/someofthethings/create-a-websocket-clientserver-setup-with-angular-socketio-and-ionic-pt1-nodejs-websocket-server-1j0m</link>
      <guid>https://dev.to/someofthethings/create-a-websocket-clientserver-setup-with-angular-socketio-and-ionic-pt1-nodejs-websocket-server-1j0m</guid>
      <description>&lt;h2&gt;
  
  
  First Blog Series Rambling
&lt;/h2&gt;

&lt;p&gt;After 10 years in the software development industry this will be my first prop blog series. I’ve written a few articles on the topic but they were a long time ago, before I knew that much and I ended up deleting them I think, because they really weren’t that great (or at least forgot where I put them up and isn’t that basically the same thing). This is the first time I’m decided to spend a long time just writing a whole bunch.&lt;/p&gt;

&lt;p&gt;I’m decided to do this so I contribute to the number of quality coding tutorials as there always seem to be gaps when looking over the web for things I want to do. If I’m honest a lot of the motivation is also to build some rep online so hopefully score some good freelance work and gain traction for my startup so I can support my wife and our new kid without having to go back to perm. Annnnnyway, you probably didn’t come here to talk about that. You came here to learn how to setup a client and server with Angular and Ionic.&lt;/p&gt;

&lt;p&gt;First off I need to say that the Ionic part is pretty much optional. There’s not likely to be a huge difference if you’re doing this in plain old Angular without all the mobile stuff. That’s what I’ve needed to do for my big project, though, so I’m going to walk you through what I’m going to do, then share the code with you at the end so you’ve got a reference point.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sections
&lt;/h2&gt;

&lt;p&gt;The tutorial is divided into three parts. First we are going to set up a Node.js app with a websocket server. Then we are going to setup an Angular app which will connect to the server via a client as part of the same app. Finally we’re going to set up a Ionic app (still Angular) which will also connect to the Node.js websocket server.&lt;/p&gt;

&lt;p&gt;The final setup will be:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdp9v19aep8j4nsbz3y8y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdp9v19aep8j4nsbz3y8y.png" alt="Architecture diagram" width="800" height="247"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ready? Lessgoooo.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;First we’re going to want to get things setup for Node.js. I’m using a Windows machine at the moment so I’ll focus on that, but I’ll cover Linux and MacOS too.&lt;/p&gt;

&lt;p&gt;Go to &lt;a href="https://github.com/coreybutler/nvm-windows" rel="noopener noreferrer"&gt;&lt;/a&gt; and download &lt;code&gt;nvm&lt;/code&gt;. Once installed you’ll want to run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvm install --lts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You won’t need the double hyphen for Windows but it doesn’t harm to include it. Follow this up by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nvm use 20.16.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or whatever the version of Node.js is that you’ve got. If you have problems later on in the tutorial, you can just do nvm &lt;code&gt;install 20.16.0&lt;/code&gt; followed by the version I’ve used above to it will work fine.&lt;/p&gt;

&lt;p&gt;This will install the LTS version of Node.js, which stands for ‘long term support’ and means we are getting the latest version that’s considered fully tested and stable.&lt;/p&gt;

&lt;p&gt;We can then check the version we’ve got by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node --version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s possible you might need to restart the console, though it worked without doing this on my system. The output should be something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;v20.16.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we’ve got Node.js installed we’ll want to create our project. Go to whichever directory you want to create the project in e.g. &lt;code&gt;cd C:\Users\peter\source&lt;/code&gt; then type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir Angular-SocketIo-and-Ionic
cd Angular-SocketIo-and-Ionic
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To create the directory and enter it. Then:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s fine to accept all the defaults. Once that’s done use either &lt;code&gt;dir&lt;/code&gt; (Windows) or &lt;code&gt;ls&lt;/code&gt; (Mac/Linux) and check that the &lt;code&gt;package.json&lt;/code&gt; file was successfully created. Then type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;echo.&amp;gt; index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(touch index.js on other systems) to create an empty index.js file. Now you’ll want to open the folder in your IDE. If you don’t have one, just go to &lt;a href="https://code.visualstudio.com/" rel="noopener noreferrer"&gt;&lt;/a&gt; and install from there. To quickly open the folder in VS Code, just type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;code .
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works on most systems. If you’re asked to install the node modules you can ignore this.&lt;/p&gt;

&lt;p&gt;Open up the &lt;code&gt;package.json&lt;/code&gt; and you should see something like the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "angular-socketio-and-ionic",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": ""
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This describes our project and, crucially for us, what packages we have in it. We’re going to want to add the socket.io package, as that will give us websocket support. To do this first open the open the package.json file in your IDE. Then open the integrated terminal in VS Code (or whatever you’re using) via either &lt;code&gt;View -&amp;gt; Terminal&lt;/code&gt; or &lt;code&gt;Terminal -&amp;gt; New Terminal&lt;/code&gt; options in the top menu, depending which you have. In the window that opens type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i --save socket.io@4.7.5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can omit the information after the @ sign but there may be compatibility issues. Now, you should notice that the &lt;code&gt;package.json&lt;/code&gt; file has opened with a few new lines which look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"dependencies": {
  "socket.io": "^4.7.5"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These means that the socket.io package has been added correctly. You should also find that a &lt;code&gt;node_modules&lt;/code&gt; folder has appeared in which contains the &lt;code&gt;@socket.io&lt;/code&gt; package along a bunch of other JavaScript packages it depends on.&lt;/p&gt;

&lt;p&gt;We are now good to add the code. At first this is going to be pretty basic and just cover the simplest possible websockets setup but in later parts of the tutorial we will also be covering super fancy (relatively speaking) stuff like CORS and security keys. For now we’ll start by adding this code to our &lt;code&gt;index.js&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createServer } from "http";
import { Server } from "socket.io";

const httpServer = createServer();
const io = new Server(httpServer, {});

io.on("connection", (socket) =&amp;gt; {
  socket.on("message", function message(data) {
    console.log("received: %s", data);
  });
});

const port = 9090;

httpServer.listen(9090);

console.log(`Server listening on port ${port}`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s break this down. The first section:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const httpServer = createServer();
const io = new Server(httpServer, {});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first line creates a standard http server. In the second we create a new websocket server, passing in the http server we created earlier. This creates a wrapper around the http server and adds websocket support to it. If you’re curious to go into more depth about how this works you can explore that Server class in your IDE, but that’s a bit too much of a rabbit-hole for us right now.&lt;/p&gt;

&lt;p&gt;The second section:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;io.on("connection", (socket) =&amp;gt; {
  socket.on("message", (data) {
    console.log("received: %s", data);
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this part we are telling the io Server instance to listen for an incoming &lt;code&gt;"connection"&lt;/code&gt; signal, and then once that is established, listen for the &lt;code&gt;"message"&lt;/code&gt; signal on the socket where it received the connection, then log the data it got to the console so we can see it.&lt;/p&gt;

&lt;p&gt;The final section:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const port = 9090;

httpServer.listen(9090);

console.log(`Server listening on port ${port}`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sets the port, tells our http server to listen on the port we set, and logs where we are listening. Sounds good — ready to test.&lt;/p&gt;

&lt;p&gt;Type this into your integrated console:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It fails:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createServer } from "http";
^^^^^^

SyntaxError: Cannot use import statement outside a module
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why? Well, as it happens we are using the new style of code module imports, whereas the npm init still creates us a &lt;code&gt;package.json&lt;/code&gt; that uses the default require imports. We need to change that. Let’s go to our &lt;code&gt;package.json&lt;/code&gt; and edit in add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"type": "module",
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You’ll want to add this as a new line, after the first curly brace, so your file should now look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "type": "module",
  "name": "angular-socketio-and-ionic",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;amp;&amp;amp; exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "socket.io": "^4.7.5"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now try running &lt;code&gt;node index.js&lt;/code&gt; again. Success! Output should be something like this, likely with a different port and random string (uuid) for your Debugger.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Debugger listening on ws://127.0.0.1:26110/bcf44d67-a3de-467e-b940-bf6512040c07
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Server listening on port 9090
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Right, so that’s all done then. There’s just one more thing we need to do for this part of the tutorial, which is test that our solution works. For this we’ll use a program called Postman. Though there is a web version of Postman, I’d recommend downloading the desktop client &lt;a href="https://www.postman.com/downloads/" rel="noopener noreferrer"&gt;here&lt;/a&gt;. This will also save you needing to create an account if you don’t want to. Once that’s installed open it up and follow the following process:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click New in the left-hand sidebar.&lt;/li&gt;
&lt;li&gt;Select Socket.IO.&lt;/li&gt;
&lt;li&gt;Type ws://localhost:9090 into Enter URL.&lt;/li&gt;
&lt;li&gt;Click Connect.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If all has gone well you’ll see the following appear (albeit with a different time) further down the screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqt2dynd4futqnxa28opa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqt2dynd4futqnxa28opa.png" alt="Connection success message" width="800" height="40"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s the connection sorted. Now we’ll check message sending works by typing test into the message tab immediately below the URL bar and hitting send. You should see:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqlogyi91bc3ga1k4hj7j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqlogyi91bc3ga1k4hj7j.png" alt="Message success output" width="800" height="36"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that’s it! You now have a fully functional Node.js websockets server! Easy huh? For now that’s all there is of the tutorial but tomorrow or Wednesday (30/07/2024–31/07/2024) I’ll be adding the next section, where I’ll be connecting this bad boy up to our base Angular App. Stay tuned…&lt;/p&gt;

&lt;p&gt;The full code for this tutorial is available here: &lt;a href="https://github.com/Some-of-the-things/Angular-SocketIo-and-Ionic" rel="noopener noreferrer"&gt;https://github.com/Some-of-the-things/Angular-SocketIo-and-Ionic&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Also available on &lt;a href="https://medium.com/@peter.carter.mail/create-a-websocket-client-server-setup-with-angular-socketio-and-ionic-pt1-node-js-9f9c8e82b379" rel="noopener noreferrer"&gt;Medium&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Follow me on Twitter &lt;a href="https://twitter.com/PeterCarterLab" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

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