First Blog Series Rambling
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.
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.
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.
Sections
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.
The final setup will be:
Ready? Lessgoooo.
Setup
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.
Go to and download nvm
. Once installed you’ll want to run:
nvm install --lts
You won’t need the double hyphen for Windows but it doesn’t harm to include it. Follow this up by running:
nvm use 20.16.0
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 install 20.16.0
followed by the version I’ve used above to it will work fine.
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.
We can then check the version we’ve got by running:
node --version
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:
v20.16.0
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. cd C:\Users\peter\source
then type:
mkdir Angular-SocketIo-and-Ionic
cd Angular-SocketIo-and-Ionic
To create the directory and enter it. Then:
npm init
It’s fine to accept all the defaults. Once that’s done use either dir
(Windows) or ls
(Mac/Linux) and check that the package.json
file was successfully created. Then type:
echo.> index.js
(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 and install from there. To quickly open the folder in VS Code, just type:
code .
This works on most systems. If you’re asked to install the node modules you can ignore this.
Open up the package.json
and you should see something like the following:
{
"name": "angular-socketio-and-ionic",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}
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 View -> Terminal
or Terminal -> New Terminal
options in the top menu, depending which you have. In the window that opens type:
npm i --save socket.io@4.7.5
You can omit the information after the @ sign but there may be compatibility issues. Now, you should notice that the package.json
file has opened with a few new lines which look something like this:
"dependencies": {
"socket.io": "^4.7.5"
}
These means that the socket.io package has been added correctly. You should also find that a node_modules
folder has appeared in which contains the @socket.io
package along a bunch of other JavaScript packages it depends on.
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 index.js
:
import { createServer } from "http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer, {});
io.on("connection", (socket) => {
socket.on("message", function message(data) {
console.log("received: %s", data);
});
});
const port = 9090;
httpServer.listen(9090);
console.log(`Server listening on port ${port}`);
Let’s break this down. The first section:
const httpServer = createServer();
const io = new Server(httpServer, {});
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.
The second section:
io.on("connection", (socket) => {
socket.on("message", (data) {
console.log("received: %s", data);
});
});
In this part we are telling the io Server instance to listen for an incoming "connection"
signal, and then once that is established, listen for the "message"
signal on the socket where it received the connection, then log the data it got to the console so we can see it.
The final section:
const port = 9090;
httpServer.listen(9090);
console.log(`Server listening on port ${port}`);
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.
Type this into your integrated console:
node index.js
It fails:
import { createServer } from "http";
^^^^^^
SyntaxError: Cannot use import statement outside a module
Why? Well, as it happens we are using the new style of code module imports, whereas the npm init still creates us a package.json
that uses the default require imports. We need to change that. Let’s go to our package.json
and edit in add the following:
"type": "module",
You’ll want to add this as a new line, after the first curly brace, so your file should now look something like this:
{
"type": "module",
"name": "angular-socketio-and-ionic",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"socket.io": "^4.7.5"
}
}
Now try running node index.js
again. Success! Output should be something like this, likely with a different port and random string (uuid) for your Debugger.
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
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 here. 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:
- Click New in the left-hand sidebar.
- Select Socket.IO.
- Type ws://localhost:9090 into Enter URL.
- Click Connect.
If all has gone well you’ll see the following appear (albeit with a different time) further down the screen.
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:
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…
The full code for this tutorial is available here: https://github.com/Some-of-the-things/Angular-SocketIo-and-Ionic
Also available on Medium
Follow me on Twitter here
Top comments (0)