Socket.io Introduction - How to Build a Chat App

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we will learn about socket IO and how it makes writing powerful real-time websocket applications easy [Music] hello and welcome I'm Dave today I will provide an introduction to socket i o and I'll provide links to all resources in the description below I'll also provide a link for you to join my Discord server where you can discuss web development with other students and you can ask questions that I can answer and receive help from other viewers too I look forward to seeing you there in the previous lesson we set up a simple mono repo with a client and server using websockets today we're going to modify our code from the previous lesson and introduce socket i o which provides some powerful features today's starter code is the completed code from lesson one in this chat app series the course resources Link in the description provides the code for each lesson so what's the difference between socket i o and simply using websockets well I'm glad you asked and they list that in their frequently asked questions now we already covered websockets and here it says websockets are awesome and it lists some of their benefits but it also says websockets are also pretty low level and developing real-time applications with websockets often requires an additional layer over them that's essentially what we get with socket i o and it gives some of the benefits here where it says they can fall back to http long polling in the case or in case the websocket connection can't be established that's one of the benefits of socket i o another is an automatic reconnection if you get your connection closed if the websocket closes acknowledgments to send some data and expect a response from the other side broadcast to all or this is important a subset of connected clients of course scale the app to multiple instances of the server that's important if you're writing a more complex application and connection recovery for short periods of disconnection you're not going to lose those things you sent they will send once it's reconnected so quite a few benefits we're just going to go over an introduction in this tutorial and look at the basic setup and some improvements over what we did in the previous lesson where we just used websockets a quick note before we get into vs code after some feedback from the first video in this series I've decided to go forward with the es6 import syntax instead of using the common JS require syntax but I could just be listening to a vocal minority and I want to make sure you understand it's not really a requirement it's more of a preference at this point because if you do not specify that you're using es6 essentially this ecmascript modules that it talks about here the default is still the common JS module loader now there's three ways you can enable the import syntax and we can do that with the MJS file extension which indicates it's a module not just a JS file also in the package.json we can specify the type and say module there or we can use the input type flag I'm going to use the package Json options so let's go back to vs code and set this up I'm now in vs code and just underneath this line line five where it says Main and index.js let's add a new line and we'll put in type and after this we'll put module and that's really all you need to do in a node.js project to enable the import syntax while we've got the package Json open I want to add some dependencies today one is a Dev dependency so let's do that first control in the backtick to open the terminal window type npm I oh you know what we're in this monorepo and so we also need to make sure that we're not up in this lesson 2 folder I need to once again CD into the server folder because that's where we actually have our package Json glad I caught that now let's go ahead and say npm I and dash capital D for Dev and add node mon nodemon is a Dev dependency that will notice anytime we save our file and it will go ahead and restart the server for us so we don't have to do those manually after that we'll go ahead and add socket i o so just npmi socket.io and this should add this as a regular dependency not a Dev dependency so now let's check our package Json file and we can see we now have a Dev dependency section with nodemon and we have a dependencies section that still has WS from the last tutorial and now it has socket IO and we're not going to use WS today so let's go ahead and open that terminal window once again and type npm uninstall WS and now this should remove that dependency and we'll check the package Json again so now we have exactly what we want socket i o here and nodemon here under Dev dependencies now let's go ahead and add a Dev start script as well so we've got the comma and now we'll add div and after Dev we're going to say node mon instead of node with the period so now we can type npm run Dev it will start our project up in Dev mode our server and before I forget the last change in this file I'm going to switch this from lesson one to lesson two with our package Json and dependencies now updated we are ready to move on to our server script and we need to change a few things here so we'll start at the top and we're no longer using WS so we can go ahead and remove that and instead I'm going to import and then curly brace create server and this is going to come from HTTP after I import create server I need to import server with a capital S and then that is going to come from socket dot IO now after that I'm going to call this we're getting too many server names in here so instead of just defining server I'm going to call this HTTP server so I get just a little bit of a difference there so we know what we're referring to and instead of this we're just going to set that equal to create server and put the operators there to call it and now that we've created a server we can use and what we'll Define IO and we'll set this equal to new server that we imported from socket IO and now we can use that server we created I'll put in the HTTP server here and now we can put in options this gives me a chance to talk about cores now if you've already gone through my node.js and express course there we discuss cores in depth and how to set all of that up for an Express server however this is different remember this is not HTTP we are now using websockets and so we need to handle cores for that as well and we can do that here in the options for socket i o so we say cores now we're going to specify what the origin is that's accepted now you might have seen this before where they just put in the asterisk and this means everything's accepted now be careful with this because this means no one is blocked they can anywhere gets access essentially they can access this from anywhere this is not what is recommended in the docs and I don't recommend leaving that wide open either instead let's go ahead and use the process.env setting for the environment that's there by default so we can say process dot EnV IR Dot and now we can look at the node environment because we are on the Node server and we'll say if it equals production and we want all lowercase here because this is a strict equals now I'm going to use a ternary statement so we put a question mark and this means if it equals production then we'll just say false because we don't want anyone outside of the domain that is currently the server is currently on to access it but if it's not if we're in development then we'll go ahead and put an array not curly braces but an array and we can put in the address that we will allow to access our socket i o server so here I'll put slash slash then I'm going to put Local Host Olin 5500 because that's where live server hosts our front-end application at however there's something that's going to come up with this and I want to leave it this way to show you the issue so I'll just leave it like this for now press alt Z to let all that wrap down so this is one line of code essentially with this ternary statement but now it's wrapping down here to the next line and now another consideration here would be if you were hosting your backend server on a different domain then you would need to give your front end domain access because it would be a cross origin resource request what cores is so you might need to list one even if it is production if you're hosting the back end on a different domain than the front end if they have a separation of concerns essentially if you're not hosting your entire application the server and the client on the same domain you would need to list something here for production of course okay with our i o server now in place and core is handled let's scroll for some more room and we need to work with this we're no longer referring to server here this is going to be IO and then we can still say dot on and we're still listening for a connection event and we still get a socket here this is all true so after the socket then we can do some different things one again this being on the server let's just log something first I'll say console.log and I want to log the user ID because as each user connects they get a different ID so we can look at that I'll just say user and then we'll use a template literal here and I can say socket dot ID so essentially every socket connection gets its own ID and then we'll just say connected so we'll get that message in the terminal after that now let's talk about what happens with the message here we can say socket dot on message that is all accurate and then we get a message here you could refer to this as data as well now we don't have to worry about this buffer anymore we're using socket IO so that's not an issue if we want to see what we have received but we could call this and let me just Ctrl D to select both we could actually call this data that we are receiving but we're not going to use socket send anymore that's not the way we want to do this so let's go ahead and say console.log and we can log this data to see what we have received here now after the data is logged instead of socket we'll say i o once again and then instead of send we'll see say dot emit now that is going to emit this message to everyone that's connected to the server essentially now what we need to put inside the emit is this is a message so we're saying what it is and then we can put a string of some sort here or whatever we want to send back so we could just send that data back or we could send a little bit more how about we go ahead and send a little bit more let's put something in the string here let's do that socket ID again but let's not it's a long string so let's not do the whole thing so here I'll put socket dot ID Dot substring and let's put the first five characters how about that now after that I'll put a colon and a space and so then we'll get the message but we'll identify whoever said it by the first five uh characters of that socket ID and then we'll have the data here that's all good but once again we need to add one more thing for the server so we got the socket where we have socket i o here with the connection and we have it emitting messages to everyone any message it receives but after that we want to go ahead and make sure the server is listening so down here we have an HTTP server that we have from above now let's say dot listen and let's say we're going to listen on Port 3500 I think I had maybe 3 000 in the last tutorial I'm switching it to 3 500 because if I remember correctly maybe a react is going to by default put an application on three thousand maybe we'll create a react app later in this series but for now we'll just put this on 3500 and then we have an anonymous function here and we can console.log and inside this log we'll just say listening on Port 3 500 and save and now our server code should be complete and now we're ready to move on to the client code but before we do that we need to import the socket i o library for the front-end application as well I am at cdnjs where we can get a library from that CDN and now let's scroll down to look at our options and of course it just shows us this first option right here which is fine it's not minified though so I would be more likely to go ahead and select the minified version down here but if you're curious what the esm means that's referring to es modules let's go ahead and look at the docs and just see what they talk about when we use this version versus this version I'm at client initialization in the docs and as I scroll down if we use that script import that we first looked at this doesn't show the minified version but we can still get a minified version then that's all we need to do we just add this to our HTML ml file but notice the esm here if we use that we need to say script type module and then in our JavaScript we would need to import IO from the name of that module essentially that's over here like they show the CDN we would put in that full CDN address essentially is where we would import that from so that's the difference when we look at those CDN files so when I go back here I'm not going to get this one because like I said I want it minified but I'm not getting this one either because I don't want to do that import today I'm just going to grab this socket.io dot Min dot JS so we can copy the URL or you can copy the full script tag here from the cdnjs.com where I'm getting these different Library links so I'll copy that script tag now let's head back to vs code and I'm back in vs code I've got the app directory open now and I have highlighted the index.html file the script tag needs to go in here before our app.js script tag because our app.js file is going to use what it gets from this Library so let's go ahead and paste this in I'll press alt Z to wrap it down you can see when we copy the script tag from cdnjs it gives us a few more attributes as well so these are in here I wouldn't know what to put with those but if you copy that it's going to put these in and possibly do an Integrity check and just have a couple of others here as well and they won't hurt anything if you put those in so I'm just going to save it as is just like I copied it from cdnjs we're ready to move on to the app.js file no changes in the CSS today okay let's start at the top we're still going to Define socket but we will not have a new websocket because we're now using socket i o so I'm going to use IO note that I don't have to import it because like I said we're not using that module we're just using that script import where I don't have to import so I can just refer to IO Auto automatically now our send message function essentially stays the same from what we had before except we're not doing socket.send we are doing socket dot emit so we are emitting a message and that's what we need to say the first thing we put in is what is this and this is a message and then we're going to send that input value once again and those are the only changes for the send message function from here we still want to call the send message function when we submit the form so that doesn't change at all but here we are going to change how we listen for messages we're no longer going to have socket dot add event listener I'm going to have socket dot on and then on is the message event so when we get a message then we are going to call this function this is very similar however we do not need to destructure this anymore we will just receive data after that we will have Li and we'll create that as we were before and now we'll set this text content equal to that same data and we will still append the LI to the UL so no more changes that's all we need okay with all of our changes in place we're now ready to start the server and then start the client application so I'm going to open a terminal window and then I'm going to make sure I'm still in that server directory so I can start the server I'll type npm run Dev which should start our server in Dev mode and that's what we've got so nodemon started the server in Dev mode and it's listing on Port 3500 that's exactly what we want now let's ensure at the top of our file note we still had localhost 3000 so I want to change this to 3 500 before we start the client application as well so now we are going to be sending this to localhost 3500 so now let's go back to the index.html and anywhere here you should be able to right click or command click and then choose open with live server if you installed that from the last tutorial and this will launch the front-end application in the browser and here it is I'm going to go ahead and open a Dev console as well with the control shift and letter I keys and now we have a cores error so let me clear this out and make sure we get that cores error again and yes this is what I expected and I want to talk about that notice the address that our app is at it's not at localhost it's at 127.0.0.1 which is the same thing it's translated to the same thing on our computer as localhost but cores reads this literally and says hey this is not the address you gave permission to access our websocket application so let's go back and look at that server code I'll pull this up and let's go to the index.js for the server and you can see for Cores we're only allowing localhost we did not put in that other address so I'm going to copy this Ctrl C here we could just change it but let's go ahead and put in both I'll paste in that same address I'm going to change this now to 127.0.0.1 so no matter if I use that or I use localhost it should now allow it so after I save open the terminal we can see well we can see nodemon already restarted the server listening on Port 3500 and we can see our front-end application already connected because here is the console log message so here's that long string that is the socket ID and it's now connected if we go back and look at the code we can see we had that console log right here so let's go to our application now on the front end here there's no more errors when I refresh no cores errors everything is good so that's good let's open this same application now in a second window here a second tab get this open in both and now I'm going to drag these so I can have both visible I've got one here on the right the one on the left will be a little bit bigger from the way I'd shared my screen but that's fine here I'm going to send a message I'm just going to say hey there and press enter to send notice it appeared on both screens so somebody that opened the front end application over here is different than somebody over here and we can tell that when this person sends a message and they have a different ID say hi and now you can see that this ID of course being different than that and now it was sent to both as well so you can see what you typed in a chat message and of course they can see what you typed as well this is a very very basic socket i o chat application so if this was all you're looking for I guess you're already all the way there but we can do much more with this as well and we're going to learn in future tutorials how to send messages to other specific users and chat rooms and all of those things show how somebody's typing and the other person can see that they're typing that oh yeah they're thinking about what they're going to send me all of that good stuff that you like to see in chat applications I also thought about adding the express server today but I think I'll do that in the next tutorial as well remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 24,962
Rating: undefined out of 5
Keywords: socket.io introduction, socket, socket.io, io, websocket, websockets, node.js, nodejs, javascript, intro, introduction, intro to socket.io, introduction to socket.io, socket.io intro, socket.io server, node.js socket.io, socket.io node.js, socket.io chat app, how to build a chat app, how to build a chat app with socket.io, building a chat app, building a chat app with socket.io, node.js app, node.js chat app, socket.io node.js app, chat socket.io, chat app, socket.io chat, chat server
Id: SGQM7PU9hzI
Channel Id: undefined
Length: 21min 38sec (1298 seconds)
Published: Fri Sep 22 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.