Learn nodejs, Creating WebSockets with Socket.IO

If you create websockets with native JavaScript in the browser, they’ll work in most modern browsers. But the support for them in older browsers isn’t quite there yet. Here I’m looking up the websockets spec. on caniuse.com.

So, one of the things that we can do, is, we can incorporate a module called Socket.IO. Socket.IO is a module that will help us build websockets, that has its own client and its own server JavaScript. What Socket.IO does, is it fails back to long polling when websockets aren’t supported. So, if websockets aren’t supported in a browser, Socket.IO will still most likely work.

And, if websockets aren’t supported at your hosting company, you can actually build a websocket application that uses entirely long polling, so that you can have a socket application work where websockets are not supported. In this lesson we are going to build the exact same chat app that we’ve built previously using pure websockets.

Only this time, we’re going to use Socket.IO. The very first thing we need to do is go to the terminal and install Socket.IO. npm install socket.io and we will save this dependency to the package JSON.

Now that I have Socket.IO installed, I’m actually going to use Socket.IO with an express application. So I’ll also want to install Express. npm install Express, and I will save that to the package JSON as well. So with Express and Socket.IO installed we’re ready to build our server application.

If you navigate to your exercise files, under chapter 9, lesson 3, in the start folder, you will notice that you have an SIO-server.js file. This is where we’re going to program the Socket.IO server. You’ll also notice that you have a public folder.

And the public folder contains our client-side files. So we have an index.html, a style.css and a JavaScript folder with the client-side JavaScript that we will need to make this socket application work. Let’s start by programming the server. So go ahead and open up the SIO-server.js file. And, from the SIO server, the first thing we’re going to do is include Express. This is going to be an express server. So when you come to our homepage, we are going to serve it using Express. The next thing I’m going to do is I also need to use the HTTP module.

So I’m going to require our HTTP module. Socket.IO is going to require that we set it up with the HTTP module. Now I’m going to create an app instance of Express and I’m also going to create an HTTP server. So our server = HTTP.createServer but this time, as opposed to building the server with a callback function, I’m just going to send this server the Express app. This will create an HTTP server based on my Express application.

I’m going to tell this server to listen to port 3000. Now, the reason that we’ve done this is because we need this server to work with Socket.IO. So I’m going to create a variable for our Socket.IO instance and we are going to require Socket.IO. Socket.IO is a function, and when you invoke the Socket.IO function you need to send it the server that it should listen for incoming connections on. So here we are invoking the Socket.IO function by sending it the HTTP server that we created with the Express app.

So the other thing that I want to do, is I want to make sure that we’re using our Express static middleware to serve the static files found in the public folder. App.use we can use to wire up express.static and this is a piece of middleware that will serve our files from the public folder. So our index.html will be served when you navigate to localhost:3000 in your browser. Now, we are going to actually be using that localhost:3000 domain with Socket.IO.

With Socket.IO, we don’t actually connect to the pure websocket. Socket.IO handles all of the connections for us. So io.on(“connection”) will listen for an incoming Socket.IO connection. And then will it cause this callback function to be invoked. This callback function is going to have the socket passed to it as an argument. So this represents one socket endpoint that’s connected. And, what we’re going to do, is, as soon as a client connects, we are going to socket.emit a message event.

And the message will be “Welcome to Cyber Chat”. So, very similar to our last application. The key difference is we are not sending anything, we are actually emitting a special type of event. We are emitting a socket event here. So whenever a message is sent we can listen for a specific type of event on the client as well. So now we’re going to listen for another type of event. When a chat event occurs from a client socket, this callback function will be fired to handle it.

So we’re assuming that the user has entered a chat message. The message will be passed to this callback function as an argument. And what we can do is broadcast to all the connected sockets this message. So I’m going to go ahead and say socket.broadcast. Socket.broadcast.emit will emit an event, like a message event, to every connected socket. So, when we receive a chat message from the client, I am going to broadcast that chat message to all of the connected sockets, using socket broadcast.

The last thing I’m going to do is just log that we are starting a socket app at http://:localhost:3000. There we go. So now our socket server file is finished. The other thing that I want to do, is I need to program our socket client file. Let me show you something. If we actually navigate to our exercise files. If we take a look in the public folder, we will notice that we have some JavaScript files.

In order to use Socket.IO on the client we actually have to include the Socket.IO client JavaScript file. Now, these files are in your exercise files, but you can get them by downloading and installing them from Socket.IO or simply npm installing Socket.IO client. There is a Socket.IO client npm registry as well. So it’s very important that we have the Socket.IO client on our page. In fact, if I look at this index.html page in Sublime, we will notice that we are not only importing the main JavaScript on line 17, but we are also importing the Socket.IO client minified JavaScript on line 16.

So in order for Socket.IO to work in the browser, we need a client. But this is great. This client is going to add the functionality to make our socket application work to those browsers that do not support websockets. So let’s go ahead and program our main JavaScript file. So if you actually open your files and navigate to the public folder. In the js folder, there is a main.js file. And when we open this file up, it’s very similar to the last lesson. When the user submits the form, we are going to gather their message.

And we’re actually going to print the user’s message, this time, on line 4, as soon as they submit it. So when a user submits a message we will print it to the DOM. These two functions down here will set the title, the h1 in the DOM, and the printMessage function will create a new paragraph for each message. So what we’re going to do is, we are going to program our Socket.IO client in this main.js file. So the first thing I’m going to do is create a new socket instance using the Socket.IO client’s io function. Now, instead of sending a websocket, I’m actually going to send this io function a link to where Socket.IO is running.

Socket.IO is running with our Express app on our HTTP server, hosted at localhost:3000. So when I create a new socket I’m actually putting in the HTTP server as opposed to the websocket server, this time. Now, when we disconnect, we will just use this socket to listen for a disconnect event. And when a disconnect event occurs this callback function will be invoked. So when we disconnect, we’ll just go ahead and set the title to “Disconnected”.

Now when there’s a new connection, the connect event will fire. So this callback function will fire when we have a newly-connected socket. And we will just go ahead and set the title to “Connected to Cyber Chat”. Now, finally, when a message event occurs. And the message event is the custom event that we emitted from the server. So we can listen for specific events.

When a message event occurs, this callback function will be fired, and sent to this callback function will be the actual message text. So when the message occurs, I’m going to print it. printMessage, and we will print that message text. Now the last thing that I need to do, is when the user fills out and submits the form, we need to send a chat event back to the server. So right after we print the message here on line 18, I’m going to use the socket to emit a chat event back to the server.

And the chat event is going to take in our input.value or the message that the user has added to that input field. Great, so let’s go ahead and save this. Let’s navigate to our terminal. And clear this old terminal screen. And we can go ahead and node sio-server. And that will start our socket server. So we’re running on localhost:3000. I can go ahead and navigate to the browser. And navigate to localhost:3000. And we see our “Welcome to Cyber Chat” message has been sent and printed.

Let me go ahead and open up another browser window. So I will also go to localhost:3000 in this second browser window. And we can also see that we have another socket connected. So now, let me test to see if this chat is working. Hello world, and hello world shows up in both messages. How is it going, how’s it going shows up in both screens. So we are clearly broadcasting our messages back to the server. Whenever I send a message, like hey what’s up, this message is emitting a chat event.

The chat event goes to the server and then broadcasts that message to all connected sockets. So this is how we can build the exact same cyber chat using Socket.IO as opposed to pure websockets. This means that this application will have a broader reach.

Leave a Reply

avatar
1000
  Subscribe  
Notify of