Socket.io is a piece of middleware that makes it easy to build real time applications. It works really well with express. There are two parts to socket.io. The server and the client. You're going to need to call the server component with a require statement just like you do with any other piece of middleware and that means you'll need to install it as a dependency of your project. The client is another script that you'll have to add to your pages. Socket.io provides link you can use, which makes it easier. Once you set everything up, your app will be able to track new events for detecting connections, disconnections or even create your own events.
In addition to that, you'll need to also install another script, the client side script, that you'll have to add to your pages. Now Socket.io provides a link you can use which will make this a lot easier. Once you set everything up, your app will be able to track events and your browser will also be able to detect connections so you'll be able to communicate between the server and the client pretty easily and let other clients know that there is a connection with another user.
It's actually pretty easy to do so let's go ahead and take care of it. Alright, so first off, I need to make sure that I install Socket.io so I'm gonna go over to my terminal, just go ahead and hit control + C to stop the application from running and I'm just gonna clear things out and I can do an npm install and I want to save it as a dependency of the project so that it will be added into my package.js file so I'll do a --save and then I will put in here socket.io.
If you're on a Mac, you may need to add the pseudo command at the beginning depending on your permissions. Alright, once that's done, we can go ahead and clear this out and restart our server with npm start. It'll run our automation and wait for connections. So I'm gonna go ahead and hide this automation for right now and I'll switch back into my editor to start working on my project. Now I'm gonna need to go into the app.js file and just like with any other middleware I need to go ahead and do a require statement so we'll do a var io and require ('socket.io') and with socket.io, we'll need to add another parenthesis.
This is where you would pass options to socket.io that the falter just find for us so I'm gonna leave that blank. Now we need to connect our server to socket.io so I'm gonna scroll all the way down, this is where we create the server and so right down here, I'm gonna to say io.attach and then we'll attach our server and add a semicolon there, and now our two pieces of middleware are connected to each other and we can start detecting events.
So to detect an event we use the on method of the object so we'll say on and then we want to detect a connection. So whenever somebody connects to our application say a new user coming in with a new browser, we want to do the following so this function is going to pass along information about the connection in a variable that we're gonna call socket. So here, we can just say something like console.log and then just say User Connected and we can do a number of other detections so once we detect the connection we can detect for other events, say within the sockets, we can say something like socket.on and then disconnect and then do the same thing call a function literal here and then do something when somebody disconnects which we can say console.log('User Disconnected') but we don't really need to do this.
We can also of course detect other methods. We can even create our own events and then let any users that are connected to our server know about those events. But before we can do any of that, we're gonna need to actually plug in to the scripts so right here in the chat.js file, we need to initialize our scripts and we also need to go into our js default files where we load up all of our scripts and then add a piece of script that is essentially Socket.io's client side script.
So to do that, I'm going to go to the Socket.io website. So from the Socket.io website, which is at Socket.io, I'm going to click on this download link. You can see that you can get the client software just by using their CDN, which is the easiest way to install things so I'm gonna copy that link and I'll switch back over here and I want to make sure I load that for my chat.js script. Once I do that, I'm gonna save this and then I'll switch over to my chat.js file and at the very top, I want to go ahead and create a variable, I'll call it socket and go ahead and call the io object.
So this is gonna load all the methods into this socket variable. Once I do that, I can start detecting any kind of event and the first thing I want to do is make sure that I detect a connection so I'll do a socket.on('connect') and then execute a function here. Again another function literal and what I'm gonna do is actually put almost the entire script in there to make sure that all this execute only if there's a connection that has taken place so I'm gonna move this chat form thing in here and let me move sort of the rest of this stuff like if (chatform).
If I want to, I can leave that show message out there because it sort of separate function and then I'll just go ahead and put that in here and now this stuff will be executed only if there is a connection available so let's go ahead and test this out. I think have enough for this to be working just with the default sort of browser messages. So let's go ahead and switch back over to our application and I'm gonna refresh my page. Then I'm gonna to check my terminal, which should show some connections.
So would be nice to see the side by side, so I'm gonna sort of make my window here smaller. So you can see that as I refresh the page it will detect a user disconnecting. You have started to refresh the page and then another user connecting as well. If I open up another tab here and I go to local host 3000, I can see that there should be another user connecting to my application so even though we're in the home page the users are connecting and as I navigate, you can see some additional disconnections and connections so that is working pretty well which means we can do more interesting things and you don't always need to log things to console as users connect and disconnect but let's go ahead and make some other interesting things so how do you actually communicate in between different browsers that are connected? To do that, you can actually admit your own set of events and that set of events can do whatever you want so instead of displaying a message like we done before right here, I'm going emit a new command to any browsers that are connected to this machine.
I'm gonna say socket.admit and this will be a event that I'm gonna call postMessage so in this machine I want to tell anything that is connected to this server, that a post message event is happening and in that post message event, I'm gonna pass along some data, which is gonna be the same thing. I'm gonna pass my user nae and my message just as if I was sending that message into my browser but now it's not gonna do that because I deleted sort of the thing that was sending it to the message.
Now that I've emitted that message, it means that I can also detect that message but to do that, we need to go back into the server and have the server detect that this post message event happened. So let's go into app.js. So what I can do is actually detect this message in my server whenever my application or one of my clients emits a post message then I can execute a function and in my application itself.
So I do want to add data right here and also now I'm going to admit another custom message so this actually has to be done on the io.object so we'll issue an emit('updateMessages') and we'll pass along the data as well so this is just like any other event that would happen on this application but we're going to a cause it to take place by emitting it from within this app.js so once I have that, I'm going to go ahead and switch over to chat.js and now I can capture that event in my chat.js file so to do that I need to create an on event and I'm gonna need to place this one outside this addEventListener here and I actually want it right outside this function.
Probably a good idea to sort of comment these. So we'll place it right outside here and we'll trap that event with a socket.on('updateMessages') and that will execute a function, pass along some data and this is going to execute my showMessage function and pass along that data so let's go ahead and delete some of these spaces just to make it seem a little bit cleaner and add some comments.
So what's gonna happen here is when somebody posts into our form, then we are going to emit this message and the reason we're emitting this message and not just sort of processing the user name and the message is because we want to path that message along to any other connected users. My main application will capture that post message event and issue a message to all of the connected devices including the one that I am currently using and once that happens, then my showMessage function will take place and it will display everything to the screen.
So let me go ahead and save both of these. Gonna save this one and the other one and we'll switch back to our application. Once everything finishes reloading, we can see that if we type in a message, you can see the message and I'm going to go ahead and open up another window and we'll go to the same URL so let's put these side by side. We'll go to the chat route so we have two sort of users chatting right now and you can see that when I type something in here, the other window displays that as well and now I can say, Hello Bob, and Bob will receive the message.
It's a little confusing because everything is the same color but we can fix that pretty easily so let me go back into my application and what I want to do is in chat.js, here's where I actually define the text color by adding a class name. I have another class name for a different color and the way we're gonna do that is we're gonna to compare if the current user so let's go ahead and do that. If (chatusername) is and of course it's the value of the user name.
Field is same as the data username then I can display the message one way, which will be with this blue sort of symbol otherwise then I'll do the same thing. This time I'm gonna do bg-info and let's try text-warning and chat-text so let's go ahead and save that. Actually, there is another thing that I need to fix. This chat user name is outside of the scope of this function so you can see that I actually put these inside this if statement and that is inside this on('connect') so I'm just gonna take those out of here.
It'll be easier if I just asked for them out here. Now save these and go back into our app. Everything should be reloaded. Let's try it again. So we get two messages. You can see that on my screen, this one is green because it's mine and this one on this screen is blue because it's not this users so let's do Bob and then when I put a message here, the opposite happens because anything I type here is going to appear green to me and anything somebody else types as far as I'm concerned will appear blue.
So that's Socket.io, it gives you a whole new set of events that you can use to handle real time communications in any of your web applications.
In this course, Ray Villalobos walks through the process of creating full-featured websites with these technologies. First, find out how to install each package and leverage Node.js features from within Express. Then learn how to build a basic application with templating engines like EJS; create more flexible, modular code with includes and conditional statements; build APIs to manage HTTP requests to add and delete content dynamically; and configure more complex routing. Along the way, Ray implements features like customer feedback forms and real-time live chat, so you can see exactly what Node.js and Express are capable of.
- Handling HTTP requests with Node.js and Express
- Creating and modularizing routes
- Using templates
- Building flexible views
- Creating an API route
- Dealing with POST and DELETE requests
- Creating live chat features with Socket.IO