Este conteúdo foi traduzido por máquina para sua conveniência e a Huawei Cloud não pode garantir que o conteúdo foi traduzido com precisão. Para exibir o conteúdo original, use o link no canto superior direito para mudar para a página em inglês.
Computação
Elastic Cloud Server
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Redes
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Gerenciamento e governança
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
Cloud Operations Center
Resource Governance Center
Migração
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Análises
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
IoT
IoT Device Access
Outros
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Segurança e conformidade
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Blockchain
Blockchain Service
Serviços de mídia
Media Processing Center
Video On Demand
Live
SparkRTC
Armazenamento
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Cloud Server Backup Service
Storage Disaster Recovery Service
Scalable File Service
Volume Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Bancos de dados
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Aplicações de negócios
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Data Lake Factory
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Distribuição de conteúdo e computação de borda
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Soluções
SAP Cloud
High Performance Computing
Serviços para desenvolvedore
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
Cloud Application Engine
MacroVerse aPaaS
KooPhone
KooDrive

Exemplo

Atualizado em 2023-08-02 GMT+08:00

Cenários

Esta seção descreve a sequência de chamadas de APIs para estabelecer uma conexão WebSocket, assinar informações, enviar informações e manter a conexão.

Processo do serviço

A figura a seguir mostra o processo de estabelecimento de conexão WebSocket, assinatura e envio de informações.

Figura 1 Processo de envio de mensagens de WebSocket
  1. Uma aplicação de terceiros obtém um token de controle de reunião e o URL do servidor necessário para estabelecer uma conexão WebSocket usando o ID da reunião e a senha do host. Para mais detalhes, consulte Obtenção de um token de controle de reunião.
  2. A aplicação de terceiros usa o token de controle de medição para obter um token para estabelecer uma conexão WebSocket. Para mais detalhes, consulte Obtenção de um token para estabelecer uma conexão WebSocket.
  3. A aplicação de terceiros estabelece uma conexão WebSocket com o servidor.
  4. A aplicação de terceiros assina informações que precisam ser enviadas pelo servidor do Huawei Cloud Meeting.
  5. O servidor do Huawei Cloud Meeting envia as informações de subscrição.
  6. A aplicação de terceiros envia uma mensagem de pulsação pelo menos uma vez dentro de 180 segundos.

Exemplo de código 1

Código para o estabelecimento da conexão WebSocket, a subscrição e a entrega e recepção de mensagens

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>WebSocket Connection Establishment and Message Delivery and Receiption</title>
      <script type="text/javascript">
         function WebSocketTest()
         {
            if ("WebSocket" in window)
            {
               // Establish a WebSocket connection.
		var confID = "900964776";
		var tempToken = "&tmpToken=" + "cnr8bee7b054df0baf766d5abca1f9d3e63a5896bdb603de7a4";
		var uri = "wss://100.94.23.40:443/cms/open/websocket/confctl/increment/conn?confID=" + confID + tempToken;
               var ws = new WebSocket(uri);

               ws.onopen = function()
               {
                // WebSocket connection established. Send a subscription message.
		var senddata = JSON.stringify({
			sequence: "000000000000000002611382273415",
			action: "Subscribe",
			data: JSON.stringify({
			subscribeType: [
			"ConfBasicInfoNotify",
			"ConfDynamicInfoNotify",
			"ParticipantsNotify",
			"AttendeesNotify",
			"SpeakerChangeNotify",
			"NetConditionNotify",
			"CustomMultiPicNotify",
			"InviteResultNotify",
			"InterpreterGroupNotify",
			"NetworkQualityNotify"
			],
			confToken: "Basic Y25yYzNiNmUxNGViNTU4NDgwMjc4NmZlYzAwYmZmNjI3MTQzNTU0ODUzY2NmMzZiYmNi",
			}),
		  });
                  ws.send(senddata);
                  alert("Sending subscription message..." + senddata);
               };

               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  // alert("Data received." + received_msg);
                };                          
            }
            else
            {
               // The browser does not support WebSocket.
               alert("Your browser does not support WebSocket.");
            }
         }
      </script>
   </head>
   <body>
      <div id="meeting">
         <a href="javascript:WebSocketTest()">WebSocket connection establishment and subscription</a>
      </div>
   </body>
</html>

Exemplo de código 2

Código para estabelecimento de conexão em um cliente de WebSocket Java e entrega e recepção de mensagens

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
 
import com.google.gson.Gson;
 
public class WebSocketClientDemo extends WebSocketClient{
 
    public WebSocketClientDemo(String url) throws URISyntaxException {
        super(new URI(url));
    }
 
    @Override
    public void onOpen(ServerHandshake shake) {
        System.out.println("Hand shake!");
        for(Iterator<String> it = shake.iterateHttpFields(); it.hasNext();) {
            String key = it.next();
            System.out.println(key + ":" + shake.getFieldValue(key));
        }
    }
 
    @Override
    public void onMessage(String paramString) {
        System.out.println("receive msg: " + paramString);
    }
 
    @Override
    public void onClose(int paramInt, String paramString, Boolean paramBoolean) {
        System.out.println("Channel close!");
    }
 
    @Override
    public void onError(Exception e) {
        System.out.println("error: " + e);
    }
 
    public static void main(String[] args) throws Exception{
        try {
            // Establish a WebSocket connection.
            String confID = "900964776";
            String tempToken = "&tmpToken=" + "cnr71e9a422216efb057719001f5e210b103ca232b3c8ced73b";
            String url = "wss://100.94.23.40:443/cms/open/websocket/confctl/increment/conn?confID=" + confID
                    + tempToken;
            WebSocketClientDemo client = new WebSocketClientDemo(url);
            client.connect();
 
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println("Not open yet");
                Thread.sleep(100);
            }
 
            System.out.println("WebSocket channel connected!");
            // WebSocket connection established. Send a subscription message.
            Gson gson = new Gson();
 
            List<SubscribeType> subscribeTypes = new ArrayList<>();
            subscribeTypes.add(SubscribeType.ConfBasicInfoNotify);
            subscribeTypes.add(SubscribeType.ConfDynamicInfoNotify);
            subscribeTypes.add(SubscribeType.ParticipantsNotify);
            subscribeTypes.add(SubscribeType.AttendeesNotify);
            subscribeTypes.add(SubscribeType.SpeakerChangeNotify);
            subscribeTypes.add(SubscribeType.NetConditionNotify);
            subscribeTypes.add(SubscribeType.InviteResultNotify);
 
            SubscribeReq subscribeReq = SubscribeReq.builder()
                    .subscribeType(subscribeTypes)
                    .confToken("Basic Y25yMjFlODA4NjRmZmRhMjg0ZTIwOTYwNTg4YjI5MjMzMmY3ZDc3ZGE1YmFlNjlhZGMz")
                    .build();
            SubscribeMsgFrame subscribeMsgFrame = SubscribeMsgFrame.builder()
                    .action("Subscribe")
                    .sequence("000000000000000002611382271289")
                    .data(gson.toJson(subscribeReq))
                    .build();
 
            String jsonStr = gson.toJson(subscribeMsgFrame);
            client.send(jsonStr);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
}

Connection establishment and message delivery and reception on a Java WebSocket client
SubscribeReq.java
------
import java.util.List;
 
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
 
@Getter
@Setter
@Builder
public class SubscribeReq {
 
    /**
     * Subscription type
     */
    List<SubscribeType> subscribeType;
 
    /**
     * Meeting token
     */
    String confToken;
}

SubscribeMsgFrame .java
------
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
 
@Getter
@Setter
@Builder
public class SubscribeMsgFrame {
 
    /**
     * Message type
     */
    String action;
 
    /**
     * Random sequence number of a message
     */
    String sequence;
 
    /**
     * Message body
     */
    String data;
}

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Conteúdo selecionado

Envie o conteúdo selecionado com o feedback