Check out a free preview of the full Full Stack for Front-End Engineers, v3 course

The "Using Websockets with Express" Lesson is part of the full, Full Stack for Front-End Engineers, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Jem briefly discusses possible errors when cloning the GitHub repository and demonstrates enabling websockets on the previously created server using Express. Writing a broadcast function, broadcasting the number of clients, and welcoming new client connections are also covered in this segment..

Preview
Close

Transcript from the "Using Websockets with Express" Lesson

[00:00:00]
>> Next let's dive in and create their actual web sockets, did everybody get this far? Otherwise you're gonna have a bad time
>> There's a couple people reporting that, they're getting a permission denied for the public key, when the SSH public key could not read from the remote repository.

[00:00:21]
>> That's strange, that's public yeah it could be you don't have your SSH key set up for Git, not everybody does. So if that's the case, you can use HTTPS and then use your username password. But if you have two-factor auth, it won't work for that, which is why we use SSH for everything.

[00:00:39]
So if you're running through an error for public key that's probably it, your SSH key isn't working correctly. Or it may not be set up on your actual home machine, if you've never used GitHub before. Okay. And if you clone that repo, you'll see we did exactly that, and here's where the web socket server things come in.

[00:01:09]
I'm gonna drag this off to the side so I can remember what I did, cuz I don't have this stuff remembered off the top of my head, I'm not that smart I'm sorry. But let's walk through it together, cuz I want everybody to understand what we're doing here.

[00:01:19]
So let's get move that off over here, we're gonna jump back into our repo here, assuming your application is working. So this is the server we're gonna be using for the rest of the day, and we're gonna use it to write a database as well. So I wanna make sure my code is segmented in a way that makes sense, it is reasonable.

[00:01:39]
So I'm just gonna say /** Begin websockets. And remember, you won't remember most of the stuff later. So it's always good to either comment or code, or leave some breadcrumbs for yourself to be, okay I went through this step and I went through this step, I went through this step.

[00:02:07]
So let's start with a WebSocket, we will need one library for this because believe me, you do not want to write a WebSocket by hand, it's not that fun. We're gonna use a library and it's really basic, it's called WS a straightforward as it can get. So let's say npm i ws, it's just a WebSocket server it'll make dealing WebSockets much easier.

[00:02:32]
So once you have that installed, let's create the actual WebSocket server. So we'll say const the real original name WebSocketServer equals require ws, and we want to server from ws. And then we wanna actually give that connection a name, so we're gonna say const wss equals a new WebSocketServer.

[00:03:11]
And the server is just gonna be the server that we created above. And this server is just this server, we're just saying attach the WebSocket to the server we created with express earlier. Next WebSocket has this idea of, or has this concept of different states very similar to an HTTP request.

[00:03:38]
But we want to do actions when the WebSocket actually connects, So to do that we're gonna use listeners. I'm gonna say WebSocket on initial connection to the minute somebody connects to our server from a browser, we wanna do something. So we wanna make a respond with a function.

[00:04:03]
And I close it off early, there we go. And the function won't really, it's gonna take in Wss Or wait no sorry, I missed one it's a connection, and then it's gonna take in ws the WebSocket library itself. That'll just make it easier to parse through a little bit later, close it off I love syntax highlighting.

[00:04:33]
Okay so we created a listener, we created a WebSocket server attached to our Express server, we gave it a function called connection that will run every time it connects to a new server. We could have written this differently, we could have made this its own const function, but just as easy.

[00:04:53]
Next what do we want to happen, whenever someone connects our web server? Why don't we just log in and say, hey someone connect to our web server. So we're gonna create a shortcut, there's something called, within the WebSocket server there's some data, and one of those is clients, and one of those is size.

[00:05:14]
That's just the number of clients we have currently connected to our web server. So let's assign this to a variable, and we'll call it numClients. And when something happens, it's good to know what's going on. Otherwise we would never know what's happening to our server, if we don't log it.

[00:05:35]
So let's create a log, and we'll just say clients connected. And I'll just pass in the numClients. So this just means every time someone connects, it'll just say this person connected, we have ten clients, we have one client, we have 1,000. Just lets us know in our log, what's going on.

[00:06:10]
So now we can use a special command called the broadcast command. And the broadcast command is pretty cool, because it's gonna send a message to everybody connected. So rather than us having to iterate through every single client, broadcast will do that for us. So just for this exercise, I want every time someone connects I want everybody to know about it.

[00:06:29]
So we're gonna say broadcasts The current visitors And we'll just say numClients, and we'll just add a little colon there, just to make it look nice. So we created a function that's gonna handle a connection that every time someone connects, it's going to broadcast out to everybody that's connected, the number of clients we have.

[00:07:01]
So we still need to handle a few states, so a socket can be open, close or errored. We need to handle these different states, so we wanna, we don't need to handle them. But it's good to do something when a WebSocket connects just to prove it's connected. Now this is where we can get super creative, but for this demo we'll keep it really simple.

[00:07:21]
So we're gonna say WebSocket on, or we're actually gonna pull from ws here because these are steady states. And we see closed open, so we'll say open or by mistake ready state, which is just saying what's the state of the WebSocket, when that equals Ws.OPEN this is an if.

[00:07:54]
We're just gonna send a message to that one client that's connected, welcome to my server So in this case, we're reading from the web, the WS library itself, which is attached to every single connection. WS is gonna have a state for every connection, and we're just gonna pull from that enum of different connection states.

[00:08:22]
We're gonna use the open one, so when a WebSocket connects and it's open, we're gonna send to the client welcome to my server. And when that connection closes, so we'll say on close, so when a client closes out, give the function we'll call it close. We don't need to name it, but is just good for logging later to name your functions now keep them anonymous.

[00:08:53]
We're just gonna say console.log, a client has disconnected. And if we wanna add a little bit more spice, we can broadcast that the client is disconnected to all the clients if we want. That's about it, however I did make a mistake, I keep getting excited and I jumped ahead of myself.

[00:09:25]
We have to write the broadcast function, that's not something that exists. So normally if you want to talk to every client, you have to say WebSocket.each, and you have to iterate through them. Why don't we just make a function that does that for us and we'll just call it broadcast, which is the function we already used.

[00:09:40]
So we'll define it here, we'll attach it to wss. That equals a function. And we'll call it broadcast, cuz it's good to name our functions, and broadcast is gonna take some sort of input or data. So now we say clients, it's an interval so we can say each or for each, and that takes a function as well.

[00:10:14]
And each, again we don't have to name it, we just do for each clients whatever we wanna do. Now what we're gonna do is use that send command. We're gonna say clients, send Whatever data we have and that's it, and that's a lot. Writing a quick function is a lot faster, than trying to do wss clients each time.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now