WebSockets in 100 Seconds & Beyond with Socket.io
WebSockets in 100 Seconds & Beyond with Socket.io
#JavaScript, #LearnToCode, #CodingTips, #WebDevelopment, #Frontend, #Fullstack, #Programming, #CodeNewbie
AI Generated·May contain errors
Video Summary
AI GeneratedThis video explains how to implement real-time, bidirectional communication between clients and servers. It covers the fundamental mechanics of WebSockets, the practical advantages of using the Socket.io library for broadcasting messages, and a step-by-step guide to building a real-time group chat application using Node.js.
Build real-time features by establishing
a two-way connection between a client and a server.
Imagine an online multiplayer game where
the leaderboard is constantly changing on the server.
Now, what's the best way to show the player an updated leaderboard?
We could tell them to refresh
their browser window every few minutes to send a new HTTP request,
or we could use an interval
that ticks every few seconds to pull the server for new data.
But these options aren't ideal for
real-time data, and that's where WebSockets come in.
The first step is for the client to send an
HTTP request to the server asking to open a connection.
If the server agrees, it will send a
101 Switching Protocols response,
at which point the handshake is complete. The TCP/IP connection
is left open, allowing bidirectional messages
to pass between the two parties with very low
latency. The connection will stay open until one
of the parties drops off, then the TCP resources
can be unallocated. It's often referred to as a full duplex connection,
which is a telecommunications
term that defines how a phone line works where
both parties can send messages or talk at the
same time. Let's see this in action by creating
a real-time connection between a Node.js server
and a web browser. We'll start in our backend code
by building a WebSocket server with Node.js.
Using the ws library, we can instantiate a new server on port 8080.
Everything is event-based,
and the first event we can expect to happen
is a connection from the client. When the connection
is made, we'll have access to a WebSocket object in the callback.
With the initial handshake done,
there are two things we might want to do here.
We can listen to incoming messages, which would just
be text in this case, and then handle them accordingly
in the callback. The second thing
we might do is send a message back to the client,
which we can do with the send method. Now let's
take a look at our client-side code in the browser,
which has a built-in WebSocket class.
It's instantiated with a URL that points to the server,
but notice the WS protocol. That will
automatically trigger the handshake to open the connection,
which we can listen to as an event.
Just like on the server,
we can use the socket to both listen to and send messages,
and we now have a full duplex connection between
a front-end JavaScript app and a node back-end.
This has been WebSockets in 100 seconds,
but if you want to learn more, make sure to stay tuned,
because today we're going beyond 100 seconds
to learn all about a library called Socket.io,
and look at a couple of APIs
that might replace WebSockets in the future.
But first, make sure to like and subscribe,
and if you're into real-time apps,
check out my Firebase content on Fireship.io.
Now one of the issues that is not so obvious with our
current implementation is that the server cannot broadcast
a message out to multiple clients
simultaneously. Like for example,
a group chat room where you have multiple users passing messages
back and forth. It's definitely possible
to build something like that from scratch with WebSockets,
but there are libraries, like Socket.io in this case,
that can make features like that much easier
to implement. You can think of a WebSocket
as a low-level building block where Socket.io is a
more practical library that solves common use cases
and provides failovers to different protocols when
needed. If you're building something real-time,
there are many different options out there. You
might look into Firebase, Apollo, GraphQL, or an API like Pusher.
Once you bring a database into
the equation, real-time features can become very complex,
and using a paid service can be well
worth the money in my opinion.
In any case, let's go ahead and get started with our Socket.io project.
at this point you can open up VS Code to follow along
and access the source code on GitHub
what we're going to build here
is a bare minimum implementation of a group chat room
when a user opens up the app they can post a message
and anybody else on that same URL can
view the message and again one of the big differences
from the previous implementation
is that the message will be broadcast to all
of the connected clients as you can see in our code
we have a directory for server
and app server is the backend app is the front end in the server
directory, we'll initialize an npm project by running npm init
y. Then we only require one
dependency, which is socket.io, and we can install it with npm.
Now in the index.js file, we need to
create an HTTP server.
We can do that using the built-in HTTP library in node.
By importing it,
then calling the create server method.
However, it is worth noting that you might want to use
express here instead, which is a much more popular option
for building an HTTP server.
The next step is to import Socket.io,
which is a function, and it will take our HTTP server
object as an argument. But in this demo,
we'll be accessing the backend from a front-end browser
application. But for security reasons,
cross-origin resource sharing, or CORS, is disabled. We can
pass an object as a second argument,
and we'll set the CORS origin to anything, allowing any URL to
access our backend URL.
And now we can implement the logic for Socket.io. Just like WebSockets,
it's an event based system.
And the first event you'll likely want to listen for is the connection
of a client from the front end,
the callback will give us access to the socket object. And on that
socket, we can listen to any custom event we want.
But for simplicity, we'll just call it the message
event. When an event is emitted, we'll have access to the data,
which might be a JavaScript object or
a string. And we can handle it inside the callback here.
In this case, it'll be a string, which we
can console log, and because we have multiple clients listening
to the message event, we can
then re-emit the message so it's broadcast out to everybody.
We can do that with the io.emit method,
and then we'll pass message as the event name,
and then whatever custom text or data we want to pass
as the second argument. And that's basically all there is to it.
It's a very simple event-based
system. The final piece of code we need here,
though, is to tell our server to listen on port
8080. Then you can open up the terminal and call node
and point it to this file to run the script
and start your Socket.io server.
And now we're ready to move on to the front-end code in our
app directory here. If we open up the index.html file,
you'll notice I have a script tag here
pointing to the Socket.io CDN for version 3.0.
It's very important to understand that Socket.io
is not a direct WebSocket implementation,
which means you can't just use the built-in WebSocket
a class in the browser. Instead,
you have to use the socket.io client library, which we're doing
here through the CDN, but you can also install it with npm
and bundle it into your project if
you're using something like React or Angular.
After that, we have a script pointing to the
app.js file, which is our custom source code,
and I'm using the defer attribute to make sure it
loads after the body content.
Then in the body itself, I have an unordered list, which is where
our chat messages will appear.
And then below that I have an input for the user to type a message
and a button to send it.
And now we can move over to our JavaScript file.
The IO object will now be
globally available in the browser,
which is the socket IO client library. We can create the
connection by pointing to the URL of our server,
which is localhost 8080. And now we're ready to
start listening to events.
By calling socket.on, we can listen to the message event emitted by the
server. And we can use some imperative browser APIs here
to create a new list item element and
then append that item to the unordered list in our HTML.
And that's all it takes to create a feed of
messages in the UI. The only thing left to do is give
the user the ability to send a message.
We can handle that by listening to the click event on a button.
When clicked, we'll grab the text or
the value from the input element,
and then we'll call socket emit with the message event and the
text. Congratulations, you just built a real-time chat app
with Socket.io. Obviously, there's a lot
more to building real-time features in the real world.
Events get emitted, and then you listen
to events and handle them accordingly with functions.
Now, before we finish up, there's
one last thing I want to talk about,
and that's the relationship between WebSockets and other
APIs like WebRTC and a new experimental API called WebTransport.
First, let's talk about WebRTC,
which stands for real-time communication.
It's also a tool for building real-time experiences,
however it's geared towards browser-to-browser communication,
primarily for video and voice.
If you're building a video chat app like Zoom,
you probably want WebRTC and not WebSockets.
And another new API that people have started talking about
is WebTransport. And without
getting into the details,
it's basically a better version of WebSockets. Faster handshake,
better reliability, and stuff like that.
Its proposal is still being stabilized,
so nothing you need to know today,
but just something to have on the radar for the future.
I'm going to go ahead and wrap things up there.
If this video helped you, please like and subscribe,
consider sponsoring me on GitHub,
or becoming a pro member at Fireship.io.
Thanks for watching, and I will see you in the next one.

