In Function Compute, you can configure an HTTP trigger for a function to respond to WebSocket requests. After you configure an HTTP trigger for a function, the function works as a web server to handle WebSocket requests and returns responses to callers.
Before you start
Step 1: Create a function
Log on to the Function Compute console. In the left-side navigation pane, click Services & Functions.
In the top navigation bar, select a region. On the Services page, click the desired service.
- On the Functions page, click Create Function.
On the Create Function page, select Use Custom Runtime, configure parameters, and then click Create.
The following items describe parameters that you must configure. For other parameters that are not listed, retain the default values. For more information, see Create a function.
Function Name: Enter the name of the function. Example: websocket-demo.
Handler Type: Select HTTP Handler.
Runtime: Select Node.js 14 from the drop-down list.
Step 2: Write and deploy code
On the function details page, click the Code tab and enter function code in the code editor.
In the current directory of WebIDE in the Function Compute console, copy the following code to the index.js file. Sample code:
const WebSocket = require('ws'); const WebSocketServer = WebSocket.Server; const wss = new WebSocketServer({ host: "0.0.0.0", port: 9000, }); wss.on('connection', function (ws, req) { console.log(`[SERVER] connection()`); ws.on('message', function (message) { ws.send(`${message}`, (err) => { if (err) { console.log(`[SERVER] error: ${err}`); } }); }) });
NoteThe IP address on which the WebSocket server listens is
0.0.0.0
, which indicates all available network ports. Do not specify127.0.0.1
orlocalhost
as the IP address.The port number on which the WebSocket server listens is an integer that ranges from 0 to 65535. In most cases, the port number is greater than 1024. You must set the
port
parameter to a value that you specified for your function. By default, the value is9000
.
The following figure shows the directory structure of WebIDE.
In the WebIDE terminal, run the
npm install ws
command to install dependencies.After the dependencies are installed, the package-lock.json file is automatically generated. The following figure shows the directory structure.
Click Deploy to deploy code to Function Compute.
Step 3: Test the function
On the function details page, click the Triggers tab to view and copy the public endpoint of the trigger.
NoteAfter the HTTP trigger is created, the public endpoint remains unchanged.
Use Postman to test the function. For more information, see Postman.
Create a WebSocket request in Postman.
Copy the public endpoint to Postman and change the value of the Scheme parameter from HTTPS to WebSocket Secure (WSS).
Configure Params and Headers based on your business requirements.
Connect to WebSocket. After the connection is established, you can send messages.
Enter the messages that you want to send and check whether the function receives the messages.
After an execution timeout period elapses, the connection to WebSocket is terminated.
The following figure shows the test process.
(Optional) If FCCommonError occurs when you use Postman to test the HTTP trigger, check the authentication method of the HTTP trigger. If you do not need to authenticate access, you can set Authentication Method of the HTTP trigger to No Authentication before you perform the test.
More information
Request timeout
Function Compute does not distinguish between WebSocket requests and HTTP requests in terms of execution timeout period. If a WebSocket connection lasts longer than the specified timeout period, the WebSocket connection is forcibly terminated and the client receives status code 1006.
Keep-alive mode and reconnection upon timeout
After a WebSocket connection is established, the connection statys alive unless the connection duration exceeds the specified timeout period, and Function Compute does not disrupt the existing logic. If no data is transmitted within a period of time when the WebSocket connection is alive, the connection may be disabled by an intermediate node, such as a NAT gateway that maps internal IP addresses of clients to public IP addresses, and route configurations. In this case, the connection timeout period is not fixed. If there is no data transmitted within the timeout period, the NAT gateway may disconnect the WebSocket connection. You may need to keep the connection alive or check whether the WebSocket connection is available by using the ping and pong frames provided by the WebSocket protocol.
If you require a longer timeout period that exceeds the maximum timeout period provided by Function Compute or you want to maintain stable logic for running applications, add a re-connection mechanism in client code to handle timeouts. You can implement the preceding mechanism by using the Reconnecting-WebSocket library or the SocketIO library.
Session affinity
Function Compute is stateless. When a function receives numerous concurrent requests at the same time, Function Compute cannot ensure that requests from the same client are processed by the same container. You may need to use external storage services, such as Redis, Memcached, Apache Kafka, and databases, to maintain the status of WebSocket requests between multiple container instances.
For example, for chat-room applications, Function Compute cannot guarantee that all users are connected to the same function instance at the same time. In this case, the Pub/Sub feature of Redis can be used to configure a chat room application. When users join a chat room, they subscribe (Sub) to the channel to which the chat room belongs. When User 1 sends a message to the function, the function publishes (Pub) the message to the channel to which the chat room belongs in Redis. This way, all users in the chat room can receive the message.
Billing methods
The billing methods for WebSocket requests and HTTP requests are the same. A WebSocket request can be regarded as an HTTP request with a longer connection time. For more information about billing, see Billing overview.
For a function whose instance concurrency is 1, the billing starts when the WebSocket connection is established and ends when the WebSocket connection is terminated.
For a function whose instance concurrency is greater than 1, the billing starts when the first WebSocket connection is established and ends when the last WebSocket connection is terminated. If multiple connections exist within a period of time, the system implements billing only once.
In the following figure, the instance concurrency of a function is 2. The first request arrives at T1 and ends at T3. The second request arrives at T2 and ends at T4. The billing starts from T1 and ends at T4. From T2 to T3, fees are charged only once.
Examples
Custom runtime | Custom Container runtime |
FAQ
Additional information
WebSocket has limits on runtimes, timeout periods, and data transmission. For more information, see Limits on WebSocket.
HTTP triggers support synchronous and asynchronous invocation. For more information, see Invocation methods.
Function Compute allows you to invoke HTTP functions across origins. For information about how to process cross-origin resource sharing (CORS) requests, see CORS request processing.