Server Sent Events and Websockets. How to implement in NodeJS and HTMX

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
you probably saw the terms service and events websocket and long polling as well and you may ask yourself when to use what and how to use them in node.js hi I am Ain and today I want to explore with you these three terms take a look how to implement them in node.js and when to use what so let's directly dive in so first things first uh what are server sent events so we have the server sent event usually referred to SS what we have is the client so in our case it's a website um or in general any client and the server the server sent events are defined in the Dom events so the browser basically can subscribe to any event source that is implemented menting The Event Source interface and if you implement the Event Source interface as a server the client can connect to it and listen to the events it is very useful if you have just events that go from the server to the client the client is requesting uh request sent to the server so it's requesting the connection and then the server holds the connection open and sends data and these data are in a specific format so data they are sent from the server to the client uh and as long as the connection is open it can send data until the client closes it or the servers closing it the server send events are a bit limited because you can only send utf8 data so strings uh also you have a limitation of connections to servers to keep them open usually browsers have four to 10 connections that can be open if you have multiple windows open the connections won't extend so you still have four for the whole browser it doesn't matter how many windows you have open and this will basically remove one of the connections you can use so if you use one for this client it blocks one of the four to 10 connections that your Chrome has also it's monodirectional so as I said uh the server can just send that to the client but the client cannot answer on these data this is quite useful if you have something like stock ticker for example if you want to see the Bitcoin price live it is very like handy to not pull the data from the server because the server can inform the client that uh the data changed you can have it for new stickers so you don't have to refresh the page uh the server will inform the client web socket this is a different protocol it's basically the websocket protocol um it's a different level it's a bit it's on the IC TCP IP stack so it's a very thin transport layer and it offers very low latency though so the client is opening the connection to the server on the websocket protocol so it is Ws or secure it is WSS so this is not not HTTP or HTP s is uh it's the websocket protocol this would be like a URL for websocket and then the server will allow the connection and it send data but now the client can also send data back so it's a back and forth of the data and it's also not limited to utf8 you can also send blob or like binary data and this makes it a bit more like handy for uh many use cases for example you want to have a chat so it does not require this long polling because this basically is holding open the connection as we see in a second on the headers uh this holds open the HTTP request and pulls the data yeah and here you have very low latency and very high throughput on the uh data of the websocket and also you are not limited to these three to four connections per browser you can open more connections but uh one disadvantage you need to keep in mind is some companies blocks the websockets on their firewall some bigger companies won't allow you to use websockets but let's take a look on how we can use this implementation now in uh no shares so here we have the service andent event implementation so what we are doing is just a plain Express server we serve the public folder with the HTML in it and we create a stream endpoint this is the service and event endpoint and on request we say okay we want to keep the connection alive and the content type is event stream we inform the browser that there will be text in an event stream format and please keep the connection alive we have a local counter we start an interval and on every counter incrementation so we say event this is the type of the event and we say it's counter we can name it whatever we want and then we send a new line so this sends it to the stream and the new line say okay next line is coming and then wew write data and then afterwards we send all the data we want to send and then as you see we have double new line so this informs the browser okay now the blob is ending and the next one is coming and when the stream is closed we clear the interval now take a look at the HDMX we have the server sent event uh we name it counter and we say just connecting to the stream and on every event in this case counter we swap the content of the diff with the response of the server let's take a look how it looks like if we reload the page we see the events coming in here so the first event the second event and it's always type counter and we see the the diff content and this is also what we have in here it will just uh change the content here of the counter uh of the div with the data from the server so if we change the content here to a different content we just say counter if we reload it changes the value we can also uh set for example the counter globally to not reset on every request so as we see now it's one uh it's not resetting to zero when we refresh so it it really depends on uh the scope so we have basically this type uh part is scoped if we open a new window uh we also will not have the same counter we will have the counter of this scope yeah this is basically servers andent events uh now let's take a look how we can Implement a websocket so we import Express websocket this is an implementation or a middleware for Express to use the websocket and then we add this Express websocket to our application uh so this is basically giving the middleware the access to the application and now we can just do app do websocket and we can Implement our chat room and we have the connection to the websocket so as soon as someone is requesting the websocket connection on chat room we will see it here we will receive the websocket and now we can connect on the websocket so for example we want to connect on the message event every time a message is incoming we will receive the message and we can just [Music] console.log uh we can just [Music] console.log the uh received message and print out how it looks like and we can also send a message to the websocket let's enable the uh websocket code in our HTM X so as we see here we connect to the websocket protocol on Port 880 chatro and the ID chat room defines that we will replace the content here with the content of the websocket response with the ID of chat room and we also have a form that sends into the websocket the content of chat message so if we refresh we see um on network tab let's so uh if we reload we see the websocket connection chat room and we see there one uh where data incoming that say welcome to the chat room so we we can receive data uh HTM X is a bit interesting here so this diff will be replaced with the new diff that says has the ID of chat room so if we now send uh welcome to the chat room as a diff with the ID of chat room and close the diff we should receive yeah perfect so now we receive the message welcome to the chat room in here uh if we take a look at the data we again see okay welcome to the chat room and if we now send something in here so we write test hit enter we see okay we sent now the Jon the correct pronunciation is probably with the chat message test and then a few headers we don't uh really care about that but we can see now we received the message so what we can do now is take the message and send it back so first of all we pass the message so we need to pass the message this is a bit complicated so we need to First do to straight ring then we pass the Json and then we uh get the text message so ws. send uh send let's copy this one and we can just send back the message so we need to make it to a rich string and if we now what broke ah we cannot redeclare message so incoming par message okay let's refresh test and we see test received so we received the message in the chat room and can answer this so if we now want to have a global chat let's say uh this is coming from the database uh const messages so we have an empty messages array and we just messages push message and then we send uh as response the messages as a list so let's say we want to say unordered list and in there we send the messages list and to create this we map over the message and return the messages so we can now send the messages back and forth okay we have one thing that we have to add do join because it will per default join the uh data as with a comma separated so we don't want to have them like this okay now we have the messages uh one after another but if we now open a second window with the same top we will see no messages we have to first send something to the Ted room and if we go to the other window so if we open both in parallel we see okay now I don't updated here I just see the messages after I sent a message to get the new state but this is nothing uh not a state we want to have we want to inform uh the other window that there's a new message because this is the whole point of the web socket right so what we can do is basically uh remember the connection so we say const uh connections and when someone is connecting to our websocket we say connections. push the websocket and when there is a message we don't don't send it to this web socket we send it to all websockets so we can just say connections dot for each connection and we just do the same thing so now if we send something here it should appear in the other window as well test from left and it received on the other one and if we send something here it's back and forth so now the websocket is connected and it will send to all the connections out there as before but if we open a new one we also have to send it so we don't want to send uh this on open we want to send basically all the messages that are uh there on open so we have to uh do basically the same thing as here we just remember all the messages and do the same as here we can make this more beautiful but but to be honest we don't care now so test and everyone is receiving it and if we refresh the page we also receive the new messages uh the old messages yeah this is basically it to implement a websocket and Implement a Service andent events so it's very easy to get started with service sent events and websockets I would highly recommend you to dig into it test it out try to implement a websocket yourself uh try to play around a bit with it there's a bit more to it than I showed now but it is very important to know the concepts of websockets and service and events because if you always just use refreshing you you basically hit the server with a lot of requests that are unnecessary for example you have a queue of people who want to buy a ticket in a ticket queue you don't want the user to refresh and refresh and refresh every time to see the updated position in the queue you want to inform the browser that his que position now is I don't know 800 or something because if the user is forced to refresh to get the updated view you basically create a ton of load on your server because everyone is constantly refreshing to see his updated que position and it is way better to just inform the browser now your que position is 200 now it's 100 and now it's your turn this is how you reduce load from your server uh make the website more interactive and all in all it just makes a lot of sense to do that if you learned something new or enjoyed the video I would appreciate your like or subscribe uh because 99% of my viewers aren't subscribed yet uh if you're interested in the code I can link it in GitHub until then Happy coding and see you next time
Info
Channel: Auryn Codes
Views: 520
Rating: undefined out of 5
Keywords: nodejs, htmx, coding, development, javascript
Id: aPrrfVs9mDc
Channel Id: undefined
Length: 16min 55sec (1015 seconds)
Published: Thu Feb 08 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.