WebSocket is a communication protocol that supports full-duplex communication over a single TCP connection. WebSocket is designed to establish two-way communication between clients and servers over persistent connections. WebSocket requires fewer overheads and supports lower network latency because connections are less frequently created or closed. Compared with the traditional request-response HTTP protocol, WebSocket supports higher efficiency for real-time interactions. WebSocket is suitable for scenarios that require real-time communication. Application Load Balancer (ALB) supports WebSocket by default.
Introduction to WebSocket
Why WebSocket?
With the rapid development of Internet technologies, web applications become more diversified. Some scenarios, such as livestreaming chat and live comments, require server-side real-time push. In traditional solutions, the round-robin algorithm is used to initiate HTTP requests from client browsers to servers at a fixed interval, such as 1 second. Then, the servers return the latest data to the clients. However, this solution has a shortcoming. Clients must frequently initiate requests, which contain large HTTP headers but less useful information. The requests not only increases loads on servers but also cause a significant waste of bandwidth resources.
To address this issue, HTML5 adopts the WebSocket protocol, which establishes more efficient communication between clients and servers. WebSocket supports full-duplex communication that allows simultaneous, two-way communication between clients and servers. It enables servers to proactively push the latest data to clients without the need for client-side polling. With fewer unnecessary requests, two-way communication significantly improves the efficiency of data exchange and reduces the consumption of server and bandwidth resources while providing smoother real-time interactions for users.
WebSocket characteristics
Before a WebSocket connection can be established, the client and the server must complete a three-way TCP handshake and a special HTTP request also called handshake to upgrade HTTP connections to WebSocket connections. During the upgrade, the client and the server communicate over WebSocket instead of HTTP. Two-way communication can be established over the same WebSocket connection.
After a WebSocket connection is established, it remains open to allow two-way communication similar to sockets. WebSocket does not require a new connection or wait for a response for each round of data exchange. The persistent, low-latency connections established over WebSocket significantly improve the efficiency of data exchange.
WebSocket exchanges data between clients and servers as data frames. WebSocket messages require smaller headers and can be exchanged as text or binary data. This type of communication reduces overheads on persistent connections and improves the efficiency of data exchange. It requires less server and bandwidth resources while providing high-performance real-time interactions.
For more information about WebSocket, see The WebSocket Protocol.
Use scenarios
WebSocket is suitable for scenarios that require instant or real-time two-way communication, such as AI applications, online chatrooms, real-time notification systems, multi-play online games, and real-time message push.
Examples
A company deployed an online chat application on Alibaba Cloud. Users can visit the domain name to access the backend servers, on which the users can interact with each other. The application requires instant communication to support low-latency, high-efficiency, two-way, and real-time data exchange between users.
High concurrency and persistent connection management become challenges. As the number of users increases, the traditional HTTP model can no longer support simultaneous, real-time communication for a large number of users. Each round of data exchange requires a new connection. This model greatly increases loads on the servers and decreases the server performance.
In this scenario, the company can use ALB together with WebSocket to manage persistent connections and maintain high concurrency. The company can deploy WebSocket applications on multiple backend servers and use Redis to synchronize messages. This solution ensures service high availability and enables reliable, efficient, and real-time message push for online chatrooms.
Usage notes
HTTP listeners of ALB support WebSocket by default. In addition, ALB supports rolling updates. Configuration changes do not affect existing persistent connections.
When you use ALB, take note of the following items:
If you want to establish a connection between ALB and a backend server over a specific version of HTTP, such as HTTP/1.1, we recommend that you use web servers that support the HTTP version as backend servers.
The default timeout period of HTTP listeners is 60 seconds. If ALB does not exchange data with a backend server for 60 seconds, the connection is closed.
You can change the value of the Connection Request Timeout parameter on the HTTP listener to set the timeout period to a desired value.
To maintain a connection, you must use a keepalive mechanism to exchange packets between ALB and the backend servers every 60 seconds.
Prerequisites
An Internet-facing ALB instance is created. For more information, see Create an ALB instance.
Three Elastic Compute Service (ECS) instances are created. In this example, the ECS instances are named ECS01, ECS02, and ECS03.
WebSocket applications are deployed on ECS01 and ECS02. Redis is deployed on ECS03.
In this example, all ECS instances use the CentOS 7.9 operating system.
We recommend that you add ECS01, ECS02, and ECS03 to the same security group. If you add the ECS instances to different security groups, you must allow access to the communication ports from each other.
A domain name is registered and an Internet Content Provider (ICP) number is obtained for the domain name. For more information, see Register a generic domain name and ICP filing process.
Procedure
Step 1: Deploy applications
Deploy Redis on ECS03 and WebSocket applications on ECS01 and ECS02.
The following example shows how to deploy a test online chatroom. In this example, the ECS instances use the CentOS 7.9 operating system. The example is for reference only. Adjust the configurations for your programs and applications.
Deploy Redis on ECS03
Log on to ECS03.
Run the following commands on ECS03 to deploy and configure Redis:
# Install Extra Packages for Enterprise Linux (EPEL) sudo yum install epel-release -y # Install Redis sudo yum install redis -y # Start and enable Redis sudo systemctl start redis sudo systemctl enable redis # Check and modify the Redis configuration file to allow remote connections sudo sed -i 's/^bind 127.0.0.1$/bind 0.0.0.0/' /etc/redis.conf sudo sed -i 's/^protected-mode yes/protected-mode no/' /etc/redis.conf # Restart Redis to apply the configuration modifications sudo systemctl restart redis # Query whether Redis is running sudo systemctl status redis
If commands do not report an error and the output shows that Redis is in the active (running) state, Redis is deployed and the configurations take effect, as shown in the following figure.
Deploy a WebSocket application on ECS01
Log on to ECS01.
Run the
sudo pip3 install flask flask-socketio flask-cors redis
command to install the dependency library.Run the
vi ECS01_ws.py
command and press theI
key to enter the edit mode.Copy and paste the following code:
Press the
Esc
key and enter:wq
to save the configurations.Run the
sudo python3 ECS01_ws.py
command to execute the script.The following output indicates that the WebSocket application is enabled and uses port 5000:
Server initialized for threading. * Serving Flask app 'ECS01_ws' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on all addresses. WARNING: This is a development server. Do not use it in a production deployment. * Running on http://192.168.*.*:5000/ (Press CTRL+C to quit)
If you fail to enable the WebSocket application, check whether the specified port is occupied by another application or errors exist in the commands or code.
Deploy a WebSocket application on ECS02
Log on to ECS02.
Run the
sudo pip3 install flask flask-socketio flask-cors redis
command to install the dependency library.Run the
vi ECS02_ws.py
command and press theI
key to enter the edit mode.Copy and paste the following code:
Press the
Esc
key and enter:wq
to save the configurations.Run the
sudo python3 ECS02_ws.p
command to execute the script.The following output indicates that the WebSocket application is enabled and uses port 5000:
Server initialized for threading. * Serving Flask app 'ECS02_ws' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off * Running on all addresses. WARNING: This is a development server. Do not use it in a production deployment. * Running on http://192.168.*.*:5000/ (Press CTRL+C to quit)
If you fail to enable the WebSocket application, check whether the specified port is occupied by another application or errors exist in the commands or code.
Step 2: Configure a server group
Log on to the ALB console.
In the top navigation bar, select the region in which the ALB instance is deployed.
In the left-side navigation pane, click Server Groups.
On the Server Groups page, click Create Server Group. In the Create Server Group dialog box, configure the parameters and click Create. The following table describes only some of the parameters. Configure the other parameters based on your business requirements or use the default values.
Parameter
Description
Server Group Type
Select the type of server group that you want to create.
VPC
Select the virtual private cloud (VPC) of ECS01 and ECS02.
The ALB instance and backend servers must be in the same VPC.
In the The server group is created message, click Add Backend Server.
In the Add Backend Server wizard, add ECS01 and ECS02 as backend servers. Set the port to the port of the WebSocket applications. In this example, the WebSocket applications use port 5000.
Step 3: Add an HTTP listener
Log on to the ALB console.
In the top navigation bar, select the region in which the ALB instance is deployed.
In the left-side navigation pane, click Instances.
On the Instances page, find the ALB instance and click Create Listener in the Actions column.
In the Configure Listener step, configure the parameters. The following table describes some of the parameters. Configure the other parameters based on your business requirements or use the default values. After you configure the parameters, click Next.
Parameter
Description
Listener Protocol
Select HTTP.
Listener Port
In this example, port 5000 is used.
In the Select Server Group step, configure the parameters. The following table describes some of the parameters. Configure the other parameters based on your business requirements or use the default values. After you configure the parameters, click Next.
Parameter
Description
Server Group
Select a server group.
In the Configuration Review step, check whether the parameters are valid and click Submit.
Step 4: Add a DNS record
In actual business scenarios, we recommend that you use CNAME records to map custom domain names to the domain name of your ALB instance.
In the left-side navigation pane, choose
.On the Instances page, copy the domain name of the ALB instance.
Perform the following steps to create a CNAME record:
NoteIf your domain name is not registered by using Alibaba Cloud Domains, you must add your domain name to Alibaba Cloud DNS before you can configure a DNS record. For more information, see Manage domain names.
Log on to the Alibaba Cloud DNS console.
On the Authoritative DNS Resolution page, find your domain name and click DNS Settings in the Actions column.
On the DNS Settings tab of the domain name details page, click Add DNS Record.
In the Add DNS Record panel, configure the parameters and click OK. The following table describes the parameters.
Parameter
Description
Record Type
Select CNAME from the drop-down list.
Hostname
Enter the prefix of the domain name. In this example, @ is entered.
NoteIf you use a root domain name, enter
@
.DNS Request Source
Select Default.
Record Value
Enter the CNAME, which is the domain name of the ALB instance.
TTL
Select a time-to-live (TTL) value for the CNAME record to be cached on the DNS server. In this example, the default value is used.
Step 5: Verify the result
Prepare two computers that have different IP addresses and support Internet access. Send messages from browsers on the computers to test whether the ALB instance can push the WebSocket messages in real time.
Visit
http://Domain name:5000
from the browsers to access the online chatroom.The following figure shows that the chatroom is accessible.
If you open the developer tools on your browser, you can find that WebSocket communication is established on the Network tab.
Enter a username and click Set as Username.
Enter a message and click Send. Repeat this operation on multiple computers.
The following figure shows that messages from different computers are displayed on the browsers.
The preceding tests show that ALB can push WebSocket messages in real time while maintaining high availability.
FAQ
How do I use the WebSocket Secure protocol?
WebSocket Secure is the encrypted version of WebSocket.
By default, HTTPS listeners support WebSocket Secure. To enable WebSocket Secure, create an HTTPS listener.
Am I charged for using WebSocket?
You are not charged for using WebSocket or WebSocket Secure.
Which regions support WebSocket?
WebSocket and WebSocket Secure are supported in all regions of ALB.
References
To facilitate the tests, this topic uses a simple example to describe how to deploy Redis on an ECS instance. However, Redis server errors may cause single points of failure (SPOFs). In your production environment, we recommend that you use What is Tair (Redis OSS-compatible)? to improve application high availability. For more information, see Overview.