All Products
Search
Document Center

Implement bidirectional communication

Last Updated: Sep 16, 2020

1. Overview

Most features of a mobile application, such as user registration and commodity list retrieval, are implemented in the process in which a client sends requests to a server and then the server responds to the client. .

However, for specific features such as instant messaging, of a mobile application, a server needs to push in-app notifications to clients. In this case, a communication channel needs to be established between the server and each client, so that the server can send notifications to the clients. Bidirectional communication between a server and a client must be supported.

The architecture of a mobile application must support the bidirectional communication feature.

Usage notes

API Gateway provides the bidirectional communication feature in all regions based on the WebSocket protocol. The bidirectional communication feature is supported by SDKs for Android, Objective-C, and Java.

If you need SDKs for other programming languages, submit a ticket or search for group ID 11747055 in DingTalk and join the group to seek help.

How it works

API Gateway provides the bidirectional communication feature in all regions. To implement bidirectional communication between a server and a client, you only need to create three API operations in API Gateway, download the SDK that is automatically generated by API Gateway, and then install the SDK on the client.

The following flowchart shows the process to implement bidirectional communication between a backend service and a client by using API Gateway.

Process

(1) A WebSocket connection is established between the client and API Gateway when the client is started. After the connection is established, the client sends a message that contains its device ID to API Gateway.

(2) The client initiates a registration signaling message to API Gateway by using the WebSocket channel.

(3) API Gateway converts the registration signaling message to an HTTP request, adds the device ID of the client to a header field named x-ca-deviceid in the request, and then sends the request to the backend service.

(4) The backend service receives the HTTP request and verifies the identity of the client. If the client passes the verification, the backend service records the device ID of the client and responds to the client with HTTP status code 200.

(5) The backend service sends a server-to-client notification signaling message to API Gateway by using the HTTP, HTTPS, or WebSocket protocol. The signaling message includes the device ID of the client.

(6) API Gateway parses the server-to-client notification signaling message, finds the connection to the client whose device ID is specified in the signaling message, and then sends the notification to the client by using the WebSocket connection.

(7) If the client no longer wants to receive notifications from the backend service, the client sends a logoff signaling message to API Gateway by using the WebSocket connection. The logoff signaling message does not include the device ID of the client.

(8) API Gateway converts the logoff signaling message to an HTTP request, adds the device ID of the client to the request, and then sends the request to the backend service.

(9) The backend service deletes the device ID of the client and responds to the client with HTTP status code 200.

2. Three types of signaling messages that are used for bidirectional communication

Before you use the bidirectional communication feature of API Gateway, you must familiarize yourself with the three types of signaling messages that are used for bidirectional communication. Each type of signaling corresponds to an API operation of API Gateway. Therefore, you must first create three API operations in the API Gateway console.

2.1 Registration signaling

A registration signaling message is sent from a client to a backend service. This type of signaling serves the following purposes:

(1) Carries the device ID of the client. After the backend service receives an HTTP request that is converted from the registration signaling message, the backend service records the device ID of the client. Note that you do not need to specify the device ID of the client in the registration signaling message. The device ID is automatically generated by the SDK of API Gateway.

(2) Works as an API operation that carries a username and a password. After the backend service receives an HTTP request that is converted from the registration signaling message, the backend service checks whether the username and password of the client are valid. If the backend service responds to the client with an HTTP status code other than 200, API Gateway returns an error to the client, which indicates that the registration failed.

If a client wants to receive notifications from a backend service, the client needs to send a registration signaling message to API Gateway. If the backend service responds with HTTP status code 200, the registration is successful.

2.2 Server-to-client notification signaling

After a backend service receives an HTTP request that is converted from a registration signaling message sent from a client, the backend service records the device ID of the client. In this way, the backend service can include the device ID of the client in server-to-client notification signaling messages and sends the signaling messages to API Gateway. If the client is connected, API Gateway can send the server-to-client notifications to the client.

2.3 Logoff signaling

If a client no longer wants to receive server-to-client notifications from a backend service, the client sends a logoff signaling message to API Gateway. After the client receives HTTP status code 200, the client no longer receives server-to-client notifications from the backend service.

3. Configure bidirectional communication in API Gateway

3.1 Enable the WebSocket channel feature for an independent domain name of an API group

3.1.1 Create an API group

If you already have an API group, skip this step.

To use the basic features of API Gateway, you must first create an API group.

3.1.2 Bind an independent domain name to the API group

If you already bound an independent domain name to the API group, skip this step.

After you create an API group, you must bind an independent domain name to it. For information about how to bind an independent domain name to an API group, see Bind a wildcard domain name to an API group.

3.1.3 Enable the WebSocket channel feature for the independent domain name

After you bind the independent domain name to the API group, you must enable the WebSocket channel feature for the independent domain name.

Perform the following steps: Log on to the API Gateway console. In the left-side navigation pane, choose Publish APIs > API Groups. On the Group List page, find the API group that is bound with the independent domain name and click the group name. On the Group Details page, find the independent domain name for which you want to enable the WebSocket channel feature in the Custom Domain Name section and click Open in the WebSocket Channel Status column.

3.2 Create three API operations, one for registration signaling, one for server-to-client notification signaling, and one for logoff signaling

Create three API operations in the API group you created. For information about how to create an API operation, seeCreate an API operation .

When you create the three API operations, set the Request Type parameter based on the signaling type that corresponds to the API operation you create.

3.2.1 Create an API operation for registration signaling

A registration signaling message is sent from a client to a backend service. When you create the API operation for registration signaling, take note of the following items:

(1) We recommend that you configure two request parameters: userName and password, as shown in the following figure.

(2) The Protocol parameter must be set to WEBSOCKET.

When you create the API operation for registration signaling, you can configure the request parameters as required. Note that if a client sends a registration signaling message, the registration is successful only after the client receives an HTTP status code of 200.

3.2.2 Create an API operation for server-to-client notification signaling

A server-to-client notification signaling message is sent from a backend service to a client. When you create the API operation for server-to-client notification signaling, take note of the following items:

(1) We recommend that you do not authorize the application whose service is supported by the backend service to call this API operation. This way, the API operation can be called only by the backend service and cannot be called by clients.

(2) You can set the Protocol parameter to HTTP, HTTPS, or WEBSOCKET.

(3) This API operation is used by a backend service to send notifications to clients. Therefore, you do not need to configure a backend service for this API operation.

(4) A request parameter named x-ca-deviceid is automatically defined for this API operation and cannot be changed. This parameter must be included in each request for this API operation.

The following figure shows the page on which you can configure request information for this API operation.

3.2.3 Create an API operation for logoff signaling

A logoff signaling message is sent from a client to a backend service. When you create the API operation for logoff signaling, note that the Protocol parameter must be set to WEBSOCKET.

3.3 Generate and download an SDK

After you create the three API operations, authorize specific applications to call the API operations. Then, publish the API operations to the production environment. After the API operations are published to the production environment, choose Publish APIs > Owned APIs SDK in the left-side navigation pane. On the Owned APIs SDK Auto-Generation page, you can generate and download the SDK of the API group to which the three API operations belong.

You can download SDK for Android and install it on a client. Then, the client can use this SDK to establish a WebSocket connection with API Gateway, send a registration signaling message, and receive server-to-client notifications from the backend service. In addition, you can download SDK for Java and install it on the backend service. The backend service uses this SDK to send notifications to the client. The two SDKs work together to implement bidirectional communication. The following figure shows the Owned APIs SDK Auto-Generation page on which you can download SDKs.

3.4 Use the SDK on a client to send a registration signaling message and receive server-to-client notifications

After you download SDK for Android, you must carefully read the ReadMe.txt file and install and use the SDK as instructed.

The SDK is automatically generated by API Gateway and contains all the API operations in the API group. You can find the API operation for registration signaling and call the API operation to send a registration signaling message from a client. The following code snippet is an SDK call example. In this example, a WebSocket channel is established and initialized between the client and API Gateway when a client is started. A function named onNotify is created to notify the client of sending server-to-client notifications. When the backend service sends a notification to the client, the SDK calls the onNotify function to notify the client. Another function named registerWebsocketTest is also provided for external calls.

public class Demo_HangZhou {
    static{        
        WebSocketClientBuilderParams websocketParam = new WebSocketClientBuilderParams();
        websocketParam.setAppKey("12345678");
        websocketParam.setAppSecret("12345678");
        websocketParam.setApiWebSocketListner(new ApiWebSocketListner() {
            @Override
            // When the backend service sends a notification to the client, the SDK calls the onNotify function to notify the client.
            public void onNotify(String message) {
                System.out.println(message);
            }

            @Override
            public void onFailure(Throwable t, ApiResponse response) {
                if(null ! = t){
                    t.printStackTrace();
                }

                if(null ! = response){
                    System.out.println(response.getCode());
                    System.out.println(response.getMessage());
                }

            }
        });

        WebSocketApiClient_hangzhou.getInstance().init(websocketParam);


    }



    public static void registerWebsocketTest(){
        WebSocketApiClient_hangzhou.getInstance().register("fred" , "123456" , new ApiCallback() {

            @Override
            public void onFailure(ApiRequest request, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ApiRequest request, ApiResponse response) {
                try {
                    System.out.println(getResultString(response));
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });
    }
}	

3.5 Use the SDK on a backend service to send notifications to a client

After a backend service receives an HTTP request that is converted from a registration signaling message, the backend service records the device ID of the client that is included in the request. To send notifications to the client, the backend service only needs to send a request to API Gateway to call the API operation for server-to-client notification signaling. The following sample code demonstrates how to call the API operation:

public class Demo_Hanzhou {
	
	    static{
	        HttpClientBuilderParams param = new HttpClientBuilderParams();
	        param.setAppKey("123456");
	        param.setAppSecret("123456");
	        HttpApiClient_BeiJing.getInstance().init(param);
	
	    }
	
	    public static void HanZhouNotifyTest(){
	        HttpApiClient_HanZhou.getInstance().notify("NotifyContent" , new ApiCallback() {
	
	            @Override
	            public void onFailure(ApiRequest request, Exception e) {
	                e.printStackTrace();
	            }
	
	            @Override
	            public void onResponse(ApiRequest request, ApiResponse response) {
	                try {
	                    System.out.println(response.getCode());
	                }catch (Exception ex){
	                    ex.printStackTrace();
	                }
	            }
	        });
	    }
}

The implementation of bidirectional communication between a client and a backend service by using API Gateway includes the following steps:

  1. Create an API group, bind an independent domain name to the API group, and then enable the WebSocket channel feature for the independent domain name.

  2. Create three API operations, one for registration signaling, one for server-to-client notification signaling, and one for logoff signaling. Then, authorize applications and publish the API operations to the production environment.

  3. Configure the registration logic and logoff logic for the backend service. Then, download SDK for Java in the API Gateway console and install the SDK on the backend service. The backend service uses SDK for Java to send notifications to the client.

  4. Download SDK for Android in the API Gateway console and install the SDK on the client. When the client is started, a WebSocket connection is established between the client and API Gateway. The client sends a registration signaling message by calling the API operation that corresponds to the signaling. After the registration is successful, the client can receive server-to-client notifications.

For information about how an SDK implements bidirectional communication, see Understand how an SDK implements bidirectional communication.

The following flowchart, which is originally provided in the linked topic, helps you better understand how bidirectional communication works.

If you encounter difficulties when you configure bidirectional communication in API Gateway, search for group ID 11747055 in DingTalk and join the group to seek help. The DingTalk group name is API Gateway-Customer Service.