localhost 127.0.0.1
) and wait to receive UDP packets.onConnectSuccess()
callback is triggered. We recommend you create a data channel for the business client after this callback.sendMessage()
to send a data packet customized by the business. The UDP onMessage()
callback API.let timer = null;const { sendMessage, code } = await TCGSDK.createCustomDataChannel({destPort: xxxx, // The recommended port range of destPort is 10000–20000.onMessage: (res) => {console.log('CustomDataChannel onMessage', res);// The receipt of this callback indicates that the cloud application has been successfully initiated and successfully transmitted data to the web end. You can use clearInterval and send data normally afterwards.// clearInterval(timer);},});// The code value 0 indicates successful establishment of a data channel between the web end and the cloud. However, the cloud application might not yet have been fully initiated (prohibiting data transmission). The web end can dispatch initial data via setTimeout/setInterval/polling, until the cloud application responds normally.if (code === 0) {// Send custom data.sendMessage('test');}if (code === 1 || code === -1) {// Retry upon failed creation.// timer = setInterval(() => {// sendMessage('test');// }, 5000);} else {// Contemplate re-establishing the data channel.}
int main() {int udp_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);if (udp_socket_fd == -1) {printf("socket failed!\\n");return -1;}// Set the destination IP address.struct sockaddr_in bind_addr = { 0 };bind_addr.sin_family = AF_INET;bind_addr.sin_port = htons(xxxx); // The recommended port range in htons(xxxx) is 10000–20000.bind_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); // Bind the IP// Bind the port.int ret = bind(udp_socket_fd, (struct sockaddr *)&bind_addr, sizeof(bind_addr));if (ret < 0) {perror("bind fail:");close(udp_socket_fd);return -1;}// Start to wait for a client message.struct sockaddr_in upstream_addr = { 0 }; // Address used to store the CAR proxy.int len = sizeof(upstream_addr);char buf[1024] = { 0 }; // Receive buffer.while (true) {ret = recvfrom(udp_socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&upstream_addr, &len);if (ret == -1) {break;}// buf is the message "test" sent by the frontend.// upstream_addr can be subsequently used to send messages to the frontend.const char* response = "response";sendto(udp_socket_fd, response, strlen(response), 0, (struct sockaddr *)&upstream_addr, sizeof(upstream_addr));}return 0;}
onMessage
callback, you can cancel the polling and then send the data normally.sendMessage()
API supports data types such as string and ArrayBuffer.
Was this page helpful?