Web sockets are a type of computer communication protocol that allows for full-duplex, or two-way, communication over a single TCP connection. This means that data can be sent from the client to the server and from the server to the client without having to open a new connection each time. Web sockets are often used for applications that require real-time updates, such as chat applications, stock tickers, and gaming applications.
Web sockets use a handshake protocol to establish a connection between the client and the server. Once the connection is established, the client and server can send messages back and forth without having to go through the handshake process again. The messages are sent over an existing HTTP connection, which means that web sockets can be used with any existing web infrastructure. Once the connection is established, it is kept open until either the client or the server decides to close it. This is different from HTTP, which opens and closes a connection for each request and response
Because web socket connections are kept open, there is no need to establish a new connection for each request and response. This reduces latency and makes communication feel more immediate.
Keeping a connection open requires less bandwidth than opening and closing a connection for each request and response.
As we mentioned before, web sockets allow for full duplex communication. This means that both the client and the server can send messages at the same time without having to wait for a response first.
The benefits of reduced latency and full duplex communication make web sockets well suited for real-time applications such as chat or gaming.
Web sockets require more resources than other protocols such as HTTP. This means that they may not be suitable for use in applications with large numbers of users or with constrained resources.
Web sockets can be difficult to debug because messages are often transmitted asynchronously, which can introduce race conditions
There are two main web socket protocols: ws:// and wss:// . The ws:// protocol uses unencrypted connections, while the wss:// protocol uses encrypted connections. You should always use wss:// in production because it helps protect your data from being intercepted by third parties.
When designing a system that uses web sockets, you will need to decide which protocol to use. If you are building an internal tool for your company, you may be able to get away with using ws:// . However, if you are building a public facing application, you will need to use wss:// .