Building a Chat App - Intro to WebSockets

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we'll learn about websockets and how they allow you to add realtime features to your [Music] applications hello and welcome I'm Dave today I will provide an introduction to websockets 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 today we're going to set up a simple mono repo featuring a front-end application that communicates with the server using websockets so what are websockets well you can picture a websocket connection like a phone call I'm here on Google Images and there's many different images explaining websockets you can see that's just what I search for I'm just using the Wikipedia image that you see here and you can see it starts with a handshake between the client and the server after that biral messages are open and persistent so it's a lot like a phone call compared to when we have that request response interaction with HTTP that you're probably used to this allows bidirectional communication and that makes websockets very useful for applications that need to broadcast immediate updates so for example a chat application is a common application where real-time bidirectional data flow is needed for today's project you will need to have nodejs installed if you don't have it currently installed go to nodejs.org that you see up here in my browser bar and you'll want to download the LTS version whatever is recommended for most users currently if you're watching this at a future date it may be a higher number than you have right there now I've got VSS code open for my code editor and I'm going to open a terminal window to start out with control and the back tick and note that I'm in an empty folder that I've created on my computer named ws-1 you could create a folder and name it whatever you want to but just start out with an empty folder today and then open that folder in vs code and then once you open a terminal window you want to check to see if you have node installed so I'm going to type node DV to check my version and you can see I currently have version 18.1 15.0 I think I just saw the latest was 1817 as of the making of this video I'll probably upgrade soon but maybe you are watching this in the future and have a newer version that is fine too just make sure you have node installed and it tells you some version there and now that we're in our empty folder let's create a couple of directories over here in the file tree I'll just click the new directory icon and I'll name the first one server because we're going to have two different projects going in this mono repo we're going to have a server and then we're also going to have a front-end application so I'll create another directory and name it app and now let's once again open a terminal window I press control and the back tick to do that and after I have done that I'm going to CD in to the server directory so I need to type CD and then SLS server you could probably also just type server either way you want to make sure you're now in the folder that you named I named mine ws-1 and then server so I'm inside the server directory here in my terminal window and I want to initialize the project with node package manager and to do that I type npm and if you installed node you should also have node package manager installed and then you want init and I'm going to type-y so it doesn't ask me questions it will just automatically create everything without the questions I'll press enter and here you can see the contents of the package Json that it just created so I'm going to close the terminal window once again let's open the server directory and now we see a package Json file in here and it has those contents now we need to use the node package WS today and you can see that's a node.js websocket library and to install it we just type npmi WS so let's go back to VSS code and do that back in VSS code I'm going to open the terminal with control backtick one more time type npmi WS to add that ws dependency which is websockets for node now I'll close this and we'll verify that we have it listed independencies here in our package Json now let's just make a couple of more changes here I'm going to change the name to ws-1 as this is the first video of my websocket series and then under scripts I want a start script so I'm going to change this to start and I'll change the contents here and it's just going to be node and then a period so this will launch our application when I type npm start and we're now ready to create our basic node.js server for websockets so let's create a new file once again in the server directory this is index.js now inside this file let's start by defining ws and there we need to require ws and that's that module we just installed as a dependency for websockets now let's define our server and that's going to equal a new ws. server and then inside of this we need to go ahead and pass an object that has the port we want to run the server on going to run this on Port 3000 today now after that let's go ahead and use that server so we'll say server.on and once we have a connection established with websockets then we'll be essentially listening for this socket and then we come over with a function and inside this function here is where we actually L listen for a message I should say so we have socket. on and then we're listening for a message and after that we'll take that message once again with a function and now inside of here we can just say socket do send and let's send that same message back so I'm going to use a template literal just pass in the value of message so whatever the server receives it's just going to essentially Echo and send it back to whoever sent it and one other thing I want to do in here just so we can come back and visit this is to go ahead and log that message and you might be surprised how the message logs on the server so we'll take a look at that as well and it was that simple to create our basic website socket server so now let's look at the frontend app I'll go ahead and let the server directory collapse here and it looks like I didn't get the index JS file in there this needs to be inside that server directory there we go so now it's all in the server directory I'm glad I looked at that and now inside the app directory here we need to create some files we'll start with an index.html file and now with VSS code we can type an exclamation mark which is an imit abbreviation and you can see I have got some help here showing what it's going to create so I'm going to press Tab and it instantly gives me this outline the skeleton of an HTML document I'm going to press alt Z so anything that was scrolling off the screen wraps down to the next line now here I'm going to change the document title to websockets and after that we're also going to need to import some files that we will be creating so we will create a CSS file so this is going to be href inside of here just style. CSS I'm just going to put it in the same app directory I'm not going to have a separate directory I'll give this the real stylesheet here and after that we're also going to have a script tag so we'll say script and now the script is going to have the source and that's going to be the JS file we create and that's just going to be named app.js today and after that I want to also set the defer here we could set that before or after but that means just don't load the JavaScript until everything else is essentially loaded make sure we have the Dom loaded before we load the JavaScript so that's also important so those are the basic things we want now let's look at the body here and we're going to put in a simple form and then inside this form and I don't need the action attribute that was added there quickly so I'll just remove that but inside of this form I do need an input it defaults to type text and that's exactly what I want so placeholder here I'm just going to set this equal to your message then after that input we need a submit button so I'll just say button and here I'll put send right there and that's essentially all we need for the HTML except where we're going to display the messages that we receed back from the server they'll go inside an unordered list and we'll create those list items with our JavaScript so we don't need to add any more there that is all we need for our HTML file but we do need to create these files that we are referencing here as well so let's start with that style.css and I'm just going to paste in some basic CSS here this is available in the GitHub repo that's Linked In the description of course you can add your own CSS this is not a CSS tutorial and you'll see the functionality with or without this CSS but what I have here is applying a font size of one and a half rim to everything on the page that would have font and I did it this way because if not you would also have to apply it separately to the input and the button as well as the body so I just dropped it here in the top got some basic colors and padding there for the body here is the form that's display Flex here is the unordered list that's display flex and then here's the input and the button with a little bit of Border radius and padding as well that's all the CSS there is now let's go ahead head and create that app.js where we can talk about websockets so we're going to start this file by defining socket and we'll set this equal to a new web socket which is a capital W and a capital S on the client side now of course this is all for the browser and this starts out WS colon and we'll have Local Host here in our development environment then we said the server was going to be on Port 3000 so we need to say that as well after that let's define a function called send message so we'll say send message and send message might receive an event so let's go ahead and put the E there for the event and now I'll say e. prevent default because we might submit a form that has our message and then we don't want to reload the page and that's what this e. prevent default allows us to do is actually submit the form without reloading the page now let's define the input inside of this function so we'll say input equals document. query selector and now we'll grab that input that is in our HTML after that let's check for a value so if we have input. value then we can take action we'll say socket. send and we'll send the input. valal and after that we'll say input. Val is going to be equal to nothing once again so after we send it we want to erase what's already in the input then after that after the if statement as well we'll put the focus back on the input and so that is our function now we'll use that function a couple of times because we'll say document. query selector and then we'll select the button so that's the submit button of the form and if it gets clicked of course it would submit the form as well so we don't really need to select the button we could just select the form let's do that and now after we get the form I'll just break this down to the next line but notice I'm not adding a space I just don't want it to wrap down awkwardly so I can do this and say dot and it will still apply so add event listener and after that we're listening for the submit event of the form and we want to call our send message function so remember when we click the send button or just we press enter inside of that input it should submit the form and it will call this send message function okay after that now we need to listen for messages that we may receive from the server so I'm going to indicate that here when I say listen for messages so you know where we're breaking apart the logic and now as we listen we'll say socket. addevent listener and we're listening for a message and if we get a message it's an event object but we can destructure that here and you get the event. DAT so we'll just destructure that to data right here then we'll use an arrow here for our function and now inside the function I'll scroll for just a little room because this is going to get a little longer let's say const Li which is our list item let's set that equal to document. create element and we're creating a list item after we've created that we can say li. text content and that's what I want right there let's set that equal to the data which is essentially the message from the server then we can say document. query selector and let's select that unordered list and now let's append child and we'll append the list item that we have created and that's really all we should need here for our client JavaScript to go ahead and be able to send messages from the form and to receive messages back from the server and display those as list items I'll save that and I noticed I didn't save that style.css so I'll save that as well looks like our frontend app is all ready to go go as well and now we need to run the applications well to do that we want to start the server first and we don't really need to look at these files I could of course display those as well but what we do need to do is open that terminal again and we should still be in the server directory down here in the terminal and we are so we can just type our npm start that we added for that script and it should start the server up so we see the node period that was indicated from the npm start and that server should now be running so now that it is we want to start our front-end application and to do that I usually use live server to launch a web application if you don't have that extension installed let's search for it really quick so you can see this over here live server and we should find it here here it is by ritwick day I've got this enabled right here lots of downloads so if you don't have this extension you might want to get that to go ahead and be able to launch your frontend applic here in Dev mode now to do that we want to go to the HTML file I can close this but now I'm going to just right click here and I should be able to choose open with live server you can see you can also make a shortcut to do that with alt L alt o or you can click go live down here as well any of that should start this application with live server I'm just going to choose open with live server there and now we'll go to the browser and here is our application it's not a lot to look at but we have our input and we have our submit button and after we send we should receive that message back from the server so let's check it out I'm just going to say hey click Send and here we received it back already from the server and we got hey so now let's go back to vs code and check the server message and see what we're getting there because remember we logged that server message here in the index online six so control and the back tick to open this up notice it's above buffer message here when we send something and then we log it on the server we get a buffer message so what if you want to actually read that message in a console log on the server as well well we need to work with a buffer just a little bit so let's change what we have here I'll say const B for buffer equals buffer. from and I'll pass in the message now after that we're not quite finished so now we need to console. log B but then also say dot two string and now we should actually log out the message here in the console as well so let's go back to the browser and we'll send another message of course since we saved anything uh live server that extension will relaunch the application when it notices any type of change so that's probably what happened here but I'll say hey once again send that and now we've got hey here let's go back and look in the terminal window and and we' still got buffer what I need to do is actually stop the server so contrl C to stop type npm start so those changes take place I'm not using nodemon if you're familiar with nodemon it will apply the changes right away and restart the server server for you I didn't do that today so I needed to restart that server now we should see the change take place so let's once again I'll reload the app here and let's type a different message like Dave and now let's see what we get when we look back at VSS code and now Dave was actually logged here to the terminal as well so just know this message will display as a buffer unless you know how to read from the buffer here on the server so we what we've got here is a mono repo this is all server side no JS and over here this is the client front-end application with HTML CSS and just vanilla JavaScript today so before we're finish today I'm going to launch another instance of the front-end application only in a second browser window and let's check it out okay I've got two instances of the front-end application running here's the one that was already running we can type hey here we get that message there but if we type something else over here like app two we get that message here notice they're not broadcasting to each other the server is communicating just like that phone call analogy I was talking about it's just between this application and the server it's not not emitting those messages or broadcasting that to everyone like say Discord would in a chat application when I would type something here like I need pizza everybody should know I need pizza but instead it's just sending it back to me and not over here so in the next tutorial in this series we're going to look at how we can do that and how socket IOD makes it very easy to accomplish 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: 28,380
Rating: undefined out of 5
Keywords: building a chat app, building a chat app with node.js, building a chat application, websockets, intro to websockets, introduction to websockets, web sockets, intro to web sockets, introduction to web sockets, websockets intro, websockets introduction, websockets tutorial, node.js websockets, chat app node.js, chat app nodejs, chat application, chat app, node.js, nodejs, websocket, realtime app, websockets vs http, monorepo, build a chat app, build a chat application, javascript, js
Id: J8xReLuBNPY
Channel Id: undefined
Length: 19min 13sec (1153 seconds)
Published: Tue Sep 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.