How I like to setup websockets in my web applications (2023)


💬 Discord
🤑 Patreon
🔔 Newsletter
📁. GitHub

My VSCode Extensions:
- theme: material community high contrast
- fonts: Menlo, Monaco, 'Courier New', monospace
- errors: Error Lens
- extra git help: Git Lens
- tailwind css intellisense
- indent rainbow
- material icon theme
- prettier & eslint
- ES7+ React Snippets


How's it going everyone, so I have been kind of doing web sockets and building out a game on my live streams on Sunday mornings, and I wanted to kind of give you a quicker, smaller overview tutorial about how do you set up websockets with vanilla.js in case Anyone is trying to learn how to do that.

Um in my project, I've been using something called socket IO, which is a library you can use to basically set up it's kind of like websockets and it's not 100 the same implementation as websock.

As you can see here, it's built on top of websockets protocol and it provides some additional guarantees, like fallback to http long polling.

So it's a library that really helps you build websockets.

If you follow the docs, it's actually pretty easy to get going um and how I got it set up.

Is I'm going to just cut to the code and show you real quick? Typically, you have a server and I'm going to be using node in Express to kind of wrap this websocket server and host a bi-directional communication between the client and the server.

So if we go to my server code, it looks like a lot of code um from the get-go, but it's really not too difficult to understand.

So, first of all, let me show you: I have a project set up with npm, so you can get this going by saying npm in it.

Y and that'll create this package Json right and inside this npm script.

I created a Dev script, which is just going to run node mon on this index file, and then I also have a start script which will just run the same index file.

So if I go down here and run this I'll say, npm run Dev.

That's going to host a server on Port 3000, which is going to run my websocket server and then also Host this public directory.

So let me, let me show you this index.js and kind of walk you through the code.

So this is requiring the Express package.

It's creating an Express service, but then it also starts setting up a websocket server using socket IO.

So we have to create an HTTP server using this HTTP module, that's built into node, and then we create a server by passing this Express app.

That gets us back.

A server object or we get a server Constructor from this socket i o package.

We pass that server into this.

We get an i o object and then we can actually start doing things with the sockets.

So all this is kind of boilerplate.

You don't have to memorize this.

You don't have to like really know.

What's going on.

You just have to copy this into your project.

But the thing that's important to understand is this: i o object.

So when you have this, i o object.

You can do dot on and you can start listening to different events that are coming in from the client.

So typically, what we do is we say on connect and then, when someone connects to your socket server, it prints out a message here, and you also have access to this socket object, which is what we're going to be using the sending messages back to the client And then um, we listen on Port 3000 and then we also host all the files that are in this public folder.

So this is just like a normal express application.

So if you're kind of familiar with Express, you should kind of be familiar with this code.

Um and let's look at the index.html, because this thing is also being hosted.

So if you look at this file, this is all there is to it.


The important part down here is that we are importing a script from socket IO, slash, socket io.js.

If you notice here, this is an absolute path, what this is doing is wherever this file is hosted, it's actually going to make a request to this localhost, 3000 or whatever.

So, just the the fact that we basically set this stuff all up, it's hosting a file for US automatically that the client can just import directly and then get set up with dockets.

So this is all the client-side code.

You really need to be able to start using sockets if you're, using vanilla.js with reactor view it's a little bit different.

You probably have to import a separate npm package, get that set up um and but then on line 15 when you call socket equals IO.

This is going to connect to the websocket server, that's running on that same host.


So if you decide to have your socket server running on a different location or a different port, then you probably have to actually pass in a URL to wherever that is.

It could be like a websocket URL like this, but anyway, if you leave it blank, it's just going to connect to your local running host, which is typically what you might want um.

So with all that being said, once you have this socket object, you can also do a DOT on connect and this is going to call a callback function when we are successfully connected to the server.

Let's go ahead and just go clear.

This console and I'm going to go to the UI and I'm going to refresh the page.

I want to show you what happens in the network tab.

So if you're not familiar with this network tab, there's a WS toggle, you can click and when you click it, it's going to print out all of your websocket connects and connections that are created against your server.

So if you look here, it's doing a request to this websocket URL localhost 3000 socket IO, and if I go to payload or messages you can see the different messages that come in from the server now.

In this case, we haven't sent any messages from the server, but we will be able to do so.

So all we're going to do is we're going to keep this basic we're going to go ahead and make a button on the front end.

I'M gon na call it ping and when someone clicks on this button I'll give it an ID of ping button, we want to make it so it sends a message to the backend that says ping okay.

So this is like how you do a ping pong setup.

So in JavaScript I can say: document.add uh.

Actually, I could say git element by ID, pass it ping button and then I can say add event listener and I can say click and then I'm going to go ahead and just do an anonymous Arrow function here and I'm going to say, socket dot emit and Then I can go just go ahead and send the first argument, which can be any string that you want in our case we're going to name it ping, but you can name this whatever you want and you can also send some data over.

So I could say like five or I could say hello or I can send an actual object.

So I'll just say, like name is Bob okay.

So now we have this event listener set up.

So when we click on the button, it should send out a ping message now at this point, we don't really need to connect anymore.

We can kind of comment that out and get rid of it.

So, let's make sure this works.

If I go and refresh the page, we should see a ping button, it's a little small.

So let me zoom in and if I click on this websocket transport, if I click on this button, you'll see down here in the bottom, it tried to send a ping request to the back end.

Okay, like this, and if I click on it.

Hopefully, it's not cut off on my screen, but you can see down at the bottom.

It sent a ping and then also a name, so we are successfully sending some data over to the back end.

Let's look at the back end now because the back end doesn't know how to process that yet right now, all we care about is connecting and disconnecting.

But if you wanted to listen on the event that we just created inside of this callback for The Connect, you can say, socket dot on and I can say ping and then we're going to get back a data object which will be whatever the the front end Decided to send over which I believe has a name in it, so I will say, got ping of now I want to point out that this socket object is the individual connection to that client.

So if you have, for example, 15 tabs open to localhost 3000 you're going to have 15 socket objects that you can actually send messages to individually now, if you wanted to broadcast an event to everybody, you can actually do that using the i o.

So I could go ahead and say: IO dot Emit and then I could put whatever message I want here and that'll broadcast it to everyone.

Who's in my websocket, there's different use cases or different things.

So just keep that in mind, but now let's go ahead and make sure that if I go back to the UI and click on that ping button that we do get back a console log, so I'm gon na go ahead and click this.

That should send the Ping to the back end and you can see the bottom of this has got a ping of Bob on the back end.

So this is fully connected, we're doing a communication from the client to the server and that works fine.

But now how do you send a message back to the client? Well, I could do socket dot Emit and I'm gon na go ahead and send a message of pong and again I can send whatever data I want.

So I can say like age of 33 or something and now what I could do is if I go back to the client, I can listen for that event.

So, instead of the socket on connect, I'm gon na go ahead and repurpose this and say socket dot on pong, and then I can also get some data here and then I'll just go ahead and say: pong uh age was data.h, I believe, is what I'm sending So now we've kind of completed the full circle before between the client in the server communication.

If I refresh this page and go ahead and go back to my console, if I click on PING notice, that I does print out pong down here right and then the server is sending back the pong h of 33.

And if I do show you one more time in the network tab, let's refresh click this and if I go down to my messages, you'll see a green up Arrow, meaning that we sent a message to the backend.

We omitted or uploaded a message and then we got back a downloaded message from the back end, which is this red down arrow, so notice.

We sent up ping and then at some point later you can actually look at the time frames and the time stamps.

About .004 milliseconds later uh, we got back a pong response.

Okay, so it's a really fast communication.

Bi-Directional communication between your your front and your back end in the use cases for this typically are related to, like you know, online chatting some type of like messaging, where you have like notifications popped down in your UI.

Obviously, online games could benefit from websockets any type of communication that needs to be as close to real time as possible um, because the other approaches would be like long polling or just polling in general, which aren't the most performant, because your UI is basically making requests Every interval every X seconds to the back end over and over and over again and there's a lot of overhead to recreate that TCP handshake in that communication.

Just to see like hey, do I have any more events.

The websockets can kind of circumvent that in become a more performant way, but keep in mind that there's additional complexity with websockets because they are stateful so to in order to use these, you have to actually have like a stateful server that is constantly running your websocket Service, which means that it kind of goes against the traditional you know, arrest being a stateless API.

So keep that in mind.

So what I would like to do on prod is sometimes I just use a pre-existing.

Websocket service Amazon, API Gateway has one there's.

One called like Pusher Agora has one where you don't have to worry about setting up all these servers yourself because setting these up and managing them and then scaling them, because when you get a lot of traffic, you have to scale them behind like a sticky load.

Balancer to make sure that your users connect to the same server every time and connect to the same websocket, since it is stateful um, because you don't want a user like on the front of the disconnect and then it reconnects them to like a different server.

Potentially, you have to kind of look at your use cases um and understand like what does your app need? Sometimes you can get away with just connecting to whatever websocket server you want and that's good enough if you've coded your application correctly but yeah that's about it.

I want to kind of share that with you all in case.

You guys are interested in like how do you actually set up a websocket communication between your client and server, and this is really how you can do it using socket.

I o now there's lower level implementations using the websocket client on the browser, and I think node has a websocket implementation.

It's just a little bit more work um.

So that's why I kind of reach for socket.

I o first and if that doesn't meet your needs, then you probably need to roll your own solution or find a different solution.


I hope you guys enjoyed watching this little video about websockets and soccer IO uh be sure to join me Discord.

If you want to talk to me directly or ask me questions or just kind of get help with your programming Endeavors and also be sure to subscribe.

Like comment, leave a press, the Bell icon um, do what you need to do anyway, have a good day and happy coding.


How to set up WebSocket? ›

In Postman, select New > WebSocket Request to open a new tab. Enter the WebSocket server URL. A WebSocket URL begins with ws:// or wss:// and our server is running on localhost:8080 . Click Connect.

What are the applications of WebSockets? ›

WebSockets are ideal for providing real-time transport and communication between AV-over-IP devices. For example, the BSS DCP-555 Template-Based Conferencing Processor uses a WebSocket connection in parallel with a standard TCP connection to allow configuration of meeting rooms via a web browser interface.

What is WebSockets and how it works? ›

WebSocket is a communications protocol for a persistent, bi-directional, full duplex TCP connection from a user's web browser to a server. A WebSocket connection is initiated by sending a WebSocket handshake request from a browser's HTTP connection to a server to upgrade the connection.

Which websites use WebSockets? ›

WebSockets Websites
  • WEBSITE. Multiuser Blocks. Patrick Schroen. HM. ...
  • WEBSITE. WeAlgo. Stef Kolman. HM. ...
  • WEBSITE. NFT of the Dead. Media.Monks. PRO ...
  • WEBSITE. Aritelia. astressence.
  • WEBSITE. The Festival of the Diaspora. oncillalabs.
  • WEBSITE. Google I/O: Adventure. Set Snail. PRO ...
  • WEBSITE. La Passation Synerg'hetic 2021. Romain Penchenat.

How to connect WebSocket to API? ›

Creating WebSocket API. In order to create the WebSocket API, we need first go to Amazon API Gateway service using the console. In there choose to create new API. Click on WebSocket to create a WebSocket API, give an API name and our Route Selection Expression.

What is the command to install WebSocket? ›

How to Install websocket-client on Linux?
  1. Open your Linux terminal or shell.
  2. Type “ pip install websocket-client ” (without quotes), hit Enter.
  3. If it doesn't work, try "pip3 install websocket-client" or “ python -m pip install websocket-client “.
  4. Wait for the installation to terminate successfully.

What is an example for WebSocket? ›

WebSocket is useful when fast connections are important. Examples include live chats on support websites, news tickers, stock tickers, messaging apps, and real-time games.

How is WebSockets implemented? ›

Client makes HTTP request to server with "upgrade" header on the request. If server agrees to the upgrade, then client and server exchange some security credentials and the protocol on the existing TCP socket is switched from HTTP to webSocket.

What is the difference between WebSocket and web server? ›

WebSocket is a protocol providing full-duplex communication channels over a single TCP connection. Where as, HTTP providing half-duplex communication. Information exchange mode of WebSocket is bidirectional. Means, server can push information to the client (which does not allow direct HTTP).

What is the basics of WebSockets? ›

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

What is the format of WebSocket URL? ›

The WebSocket resource URL uses its own custom scheme: ws for plain-text communication (e.g., ws://, and wss when an encrypted channel (TCP+TLS) is required.

What ports are used by WebSocket? ›

The well known TCP port for WebSocket traffic is 80 and 443.

Which WebSocket is best? ›

9 Best WebSocket Libraries for Node. js in 2023
  • WS.
  • SockJS.
  • Faye WebSocket.
  • Sockette.
  • Socket.IO.
  • Feathers.
  • SocketCluster.
  • WebSocket Node.
Mar 6, 2023

How do I know if my website is using WebSocket? ›

You can use the WS button to filter the list for just web socket connections. Only requests with the 101 status code (WebSocket Protocol Handshake) are visible, which indicates that the server is switching to a web socket connection. Clicking on a web socket request opens the usual sidebar to reveal additional details.

What are the advantages of WebSockets? ›

WebSockets work by initiating continuous, full-duplex communication between a client and server. This reduces unnecessary network traffic, as data can immediately travel both ways through a single open connection. This provides speed and real-time capability on the web.

How do I enable WebSocket in my browser? ›

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.

How do I send data to a WebSocket? ›

To send a message through the WebSocket connection you call the send() method on your WebSocket instance; passing in the data you want to transfer. socket. send(data); You can send both text and binary data through a WebSocket.

How do I deploy a WebSocket app? ›

First, open a terminal window and create a new project directory and then navigate to the new directory.
  1. $ mkdir sample-websocket $ cd sample-websocket. At this point, you can initialize a new npm project. ...
  2. $ npm init -y. Next, install the express and ws packages. ...
  3. $ npm install express ws.
Aug 11, 2022

How do I specify a WebSocket URL? ›

Creating a WebSocket object

The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss:// , although some software may allow you to use the insecure ws:// for local connections. Either a single protocol string or an array of protocol strings.

What tool do I need to check WebSocket? ›

Request WebSocket URL through CLI tool (wscat) or Postman. That will confirm that the server can establish connection with other clients (besides browsers) which support WebSockets. Exploratory check: server should respond with correct status codes.

Is WebSocket frontend or backend? ›

Using WebSockets to connect a backend with a frontend enables you to form long-lasting, full duplex connections for continuously streaming data. For the backend, the essential steps are: Import the library, create an node HttpServer instance, and use this instance to create a Socket.IO instance.

Is WebSocket HTTP or TCP? ›

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. The current API specification allowing web applications to use this protocol is known as WebSockets.

What is WebSocket in REST API? ›

The WebSocket API invokes your backend based on the content of the messages it receives from client apps. Unlike a REST API, which receives and responds to requests, a WebSocket API supports two-way communication between client apps and your backend. The backend can send callback messages to connected clients.

How many connections can WebSockets handle? ›

FAQs on scaling WebSockets

In theory, a server can handle up to 65,536 sockets per single IP address.

Do browsers use WebSockets? ›

WebSocket, as an IETF standard, and with a W3C browser API, is fully supported by all modern browsers: Chrome 16 + (incl. Chrome for Android)

When should I use WebSockets? ›

When to use WebSockets. Use WebSockets when you want two-way communication between two networked systems, for example when building a chat application. WebSockets are also very useful for data visualization dashboards or maps that need to reflect real-time data values.

Is WebSocket better than REST API? ›

WebSockets have a low overhead per message. They're ideal for use cases that require low-latency, high-frequency communication. REST APIs have a higher message overhead compared to WebSockets. They're best suited for use cases where you want to create, retrieve, delete, or update resources.

Do WebSockets require HTTP? ›

The WebSocket protocol uses HTTP transmitting mechanisms and starts as standard HTTP requests and responses. Inside of this communication chain, the client requests to open a WebSocket connection. If the request is successful, the client and the server start using the TCP connection as a WebSocket connection.

What are the different types of WebSockets? ›

A WebSocket frame can be one of 6 types: text , binary , ping , pong , close and continuation .

Which layer is WebSocket? ›

Web Socket Protocol

First of all, both protocols can be found at layer 7 OSI model and both are depending on the TCP architecture at layer 4 model. They are also different because RFC 6455 is declaring that the Web Socket protocol is particularly designed to be utilized over HTTP ports (443 and 80).

How to create WebSocket endpoint? ›

  1. Click File > New > Other. Under the Web category, select WebSocket Endpoint.
  2. Right-click a selected project. Select New > WebSocket Endpoint.

Can WebSocket send files? ›

You can send raw binary data through the WebSocket. It's quite easy to manage. One option is to prepend a "magic byte" (an identifier that marks the message as non-JSON). For example, prepend binary messages with the B character.

What type of protocol is WebSocket? ›

As per the conventional definition, WebSocket is a duplex protocol used mainly in the client-server communication channel. It's bidirectional in nature which means communication happens to and fro between client-server.

How long can WebSocket stay open? ›

In general, WebSocket connections can stay open indefinitely as long as both the client and server remain connected and the network is stable.

What is the difference between a port and a WebSocket? ›

"Port" is a number used by a particular software. The same port may be used in different computers/servers running same software. Port is request running on that socket and port uses socket to deliver the packet to correct application. A socket is the way a server and a client keep track of requests.

Is WebSocket TCP or UDP? ›

While WebSocket works only over TCP, WebRTC is primarily used over UDP (although it can work over TCP as well). WebSocket is a better choice when data integrity is crucial, as you benefit from the underlying reliability of TCP.

Can multiple clients connect to same WebSocket? ›

A server can open WebSocket connections with multiple clients—even multiple connections with the same client. It can then message one, some, or all of these clients. Practically, this means multiple people can connect to our chat app, and we can message some of them at a time.

Which WebSockets client is fastest? ›

In this benchmark there is one clear winner: uWebSockets-library. uWebSockets, which is written in C/C++, was the fastest performing WebSocket server both when used with Node. js and Python. The speed is impressive but so is the resource usage.

Does Chrome use WebSockets? ›

Web Sockets on Chrome is fully supported on 16-114, partially supported on 4-15, and not supported on below 4 Chrome versions. Web Sockets on Safari is fully supported on 7.1-16.4, partially supported on 5.1-6, and not supported on 3.2-4 Safari versions.

How do I get data from a WebSocket? ›

First, you need to copy your web browser's header to here and use json. dumps to convert it into the string format. After that, create the connection to the server by using create_connection . Then, perform the handshake by sending the message, and you will be able to see the data on your side.

How do I connect to WebSocket from Chrome? ›

# WebSocket binary message viewer
  1. Open the Network panel. ...
  2. Click WS to filter out all resources that aren't WebSocket connections. ...
  3. Click the Name of a WebSocket connection to inspect it. ...
  4. Click the Messages tab. ...
  5. Click one of the Binary Message entries to inspect it.
Mar 7, 2019

Which is faster HTTP or WebSocket? ›

WebSockets are typically faster than HTTP because they allow for real-time, bidirectional communication and reduce overhead by eliminating the need for new HTTP requests.

What are the weaknesses of WebSocket? ›

Drawbacks or disadvantages of Websockets

Intermediary/Edge caching is not possible with websockets unlike HTTP. ➨To build even simple protocol of your own, one can not be able to use friendly HTTP statuses, body etc. ➨If application does not require a lot of dynamic interaction, HTTP is much simpler to implement.

What is the disadvantage of WebSocket? ›

The biggest downside to using WebSocket is the weight of the protocol and the hardware requirements that it brings with it. WebSocket requires a TCP implementation, which may or may not be a problem, but it also requires an HTTP implementation for the initial connection setup.

How do I enable WebSocket in Chrome? ›

Short answer for Chrome Version 29 and up:
  1. Open debugger, go to the tab "Network"
  2. Load page with websocket.
  3. Click on the websocket request with upgrade response from server.
  4. Select the tab "Frames" to see websocket frames.
  5. Click on the websocket request again to refresh frames.

How do I use WebSocket in Chrome? ›

Chrome DevTools: View WebSocket messages interactively
  1. Open the Filter menu in the Network Panel.
  2. Select the WS filter.
  3. Select any WebSocket resource.
  4. Open the Messages pane.
Feb 5, 2019

Are WebSockets still used? ›

For now, I think there are plenty of applications already using Websocket. And there are many frameworks developed for Websockets in almost all the programming languages. They are very matured as well. Only caveat developers may think of Websocket is that, the fact that it's not HTTP.

How to send data through WebSocket? ›

WebSocket: send() method. The WebSocket. send() method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of bufferedAmount by the number of bytes needed to contain the data.

How do I connect my WebSocket to my browser? ›

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.

Which browsers support WebSockets? ›

WebSocket, as an IETF standard, and with a W3C browser API, is fully supported by all modern browsers:
  • Chrome 16 + (incl. Chrome for Android)
  • Firefox 11 + (incl. Firefox for Android)
  • Internet Explorer 10+ (incl. Internet Explorer Mobile on Windows Phone 8)
  • Safari 6 +
  • Opera 12.1 + (incl. ...
  • iOS 6.0 +
  • Blackberry 7 +

Does Chrome support WebSockets? ›

Web Sockets on Chrome is fully supported on 16-114, partially supported on 4-15, and not supported on below 4 Chrome versions. Web Sockets on Safari is fully supported on 7.1-16.4, partially supported on 5.1-6, and not supported on 3.2-4 Safari versions.

How do I use simple WebSocket client in Chrome? ›

Simple WebSocket Client is an extension for Google Chrome to help construct custom Web Socket requests and handle responses to directly test your Web Socket services.
  1. Enter the URL for your Web Socket server.
  2. Click Open.
  3. Input request text, then click Send.
Sep 12, 2014

How to create WebSocket in HTML? ›

Following is the API which creates a new WebSocket object. var Socket = new WebSocket(url, [protocal] ); Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.

What replaced WebSocket? ›

WebTransport's streams API allows you to create connections for sending ordered data. As WebTransport uses the QUIC protocol, these connections are less resource intensive to open and close than with TCP.

What replaces WebSockets? ›

While WebSockets can be used for various applications, MQTT is explicitly designed for machine-to-machine communication, which is why it's considered an alternative under these use cases. MQTT provides features like low overhead, efficient message delivery, and support for offline operation.

Is WebSocket over HTTP or https? ›

WebSocket is distinct from HTTP. Both protocols are located at layer 7 in the OSI model and depend on TCP at layer 4. Although they are different, RFC 6455 states that WebSocket "is designed to work over HTTP ports 443 and 80 as well as to support HTTP proxies and intermediaries", thus making it compatible with HTTP.

What is the basics of webSockets? ›

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

How do I deploy a WebSocket server? ›

First, open a terminal window and create a new project directory and then navigate to the new directory.
  1. $ mkdir sample-websocket $ cd sample-websocket. At this point, you can initialize a new npm project. ...
  2. $ npm init -y. Next, install the express and ws packages. ...
  3. $ npm install express ws.
Aug 11, 2022

Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 19/11/2023

Views: 5233

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.