目录

What should I do if the callback in client.on("message," (value: SocketInfo)) cannot be received when SocketServer is used?

Cause

The socket of the client is reclaimed and released. As a result, there is a high probability that the callback in client.on("message," (value: SocketInfo)) cannot be received.

Solution

Define an array, and add the socket of the client to the array when the client sets up a connection. This helps to prevent the socket from being reclaimed and released. The code snippet is as follows:

import { socket } from '@kit.NetworkKit';

let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();
// Define the array for storing socket connections.
let tcpConnectArray: socket.TCPSocketConnection[] = [];

class SocketInfo {
  message: ArrayBuffer = new ArrayBuffer(1);
  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
}

@Entry
@Component
struct CreateSocket {
  build() {
    Column() {
      Button('Create Socket').onClick(async () => {
        tcpServer.on('connect', (client: socket.TCPSocketConnection) => {
          // Save the socket of the client.
          tcpConnectArray.push(client);
          // Subscribe to events of the TCPSocketConnection object.
          client.on('close', () => {
            console.log("on close success");
          });
          client.on('message', (value: SocketInfo) => {
            // There is a high probability that the message cannot be received.
            let buffer = value.message;
            let dataView = new DataView(buffer);
            let str = '';
            for (let i = 0; i < dataView.byteLength; ++i) {
              str += String.fromCharCode(dataView.getUint8(i));
            }
            console.log('received message--:' + str);
          });
        })
        console.log('create socket Succeeded ');
      })

    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}