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. Classic Load Balancer (CLB) 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.
Example
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 CLB together with WebSocket to manage persistent connections and maintain high concurrency. The company can deploy WebSocket applications on multiple backend servers. This solution ensures service high availability and enables reliable, efficient, and real-time message push for online chatrooms.
Usage notes
HTTP listeners of CLB support WebSocket by default. In addition, CLB supports rolling updates. Configuration changes do not affect existing persistent connections.
When you use CLB, take note of the following items:
If you want to establish a connection between CLB 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 CLB 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
A CLB instance is created. For more information, see Create a CLB 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 CLB console.
In the top navigation bar, select the region in which the CLB instance is deployed.
In the left-side navigation pane, click Instances. On the Instances page, click the ID of the CLB instance that you want to manage.
On the vServer Groups tab, click Create vServer Group. On the Create vServer Group page, configure the parameters. The following table describes some key parameters. Other parameters use the default values. After you complete the configurations, click Create.
Parameter
Description
vServer Group Name
Enter the name of vServer Group RS1.
On the vServer Groups tab, find the vServer group and click Modify in the Actions column.
On the Modify vServer Group page, click Add. In the Servers panel, select ECS01 and ECS02 and set the port to the port used by the WebSocket applications. In this example, the WebSocket applications use port 5000.
On the Modify vServer Group page, select the backend servers that you add and click Save.
Step 3: Add an HTTP listener
Log on to the CLB console.
In the top navigation bar, select the region in which the CLB instance is deployed.
In the left-side navigation pane, click Instances.
On the Instances page, find the CLB instance and click Configure Listener in the Actions column.
In the Protocol & Listener step, configure the parameters. The following table describes some of the parameters. Configure the other parameters based on your business requirements. After you configure the parameters, click Next.
Parameter
Description
Select Listener Protocol
Select HTTP.
Listener Port
In this example, port 5000 is used.
In the Backend Servers step, configure the parameters. The following table describes some of the parameters. Configure the other parameters based on your business requirements. After you configure the parameters, click Next.
Parameter
Description
Server Group
Select the server group that you want to use.
In the Health Check step, click Next. You can use the default parameter values or specify values based on your business requirements.
In the Confirm step, check whether the parameters are correctly configured and click Submit.
Step 4: Add a DNS record
For domains not registered on Alibaba Cloud, you must first add the domain name to Alibaba Cloud DNS before you can create a DNS record.
If your CLB instance is internal-facing, you must first associate an Elastic IP address (EIP) with it, then create an A record to map the domain name to the EIP for Internet access.
In the left-side navigation pane, choose
.On the Instances page, find the CLB instance that you want to manage and copy the Endpoint of the CLB instance.
Perform the following steps to create an A record.
Log on to the Alibaba Cloud DNS console.
On the Authoritative DNS Resolution page, find the domain name that you want to manage, and click DNS Settings in the Actions column.
On the DNS Settings page, click Add Record.
In the Add Record panel, configure the following parameters, use the default values for all the other parameters or set them based on actual conditions, and click OK.
Parameter
Description
Record Type
Select A from the drop-down list.
Hostname
The prefix of your domain name. In this example, www is entered.
NoteIf you use a root domain name, enter @.
Record Value
Enter the A address corresponding to your domain name. In this example, the IP address of your CLB instance 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 CLB 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 the CLB instance 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 CLB.
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.