HarmonyOS socket Tcp连接connect成功后无法收到tcp.on('message')的消息

HarmonyOS
2024-12-27 17:56:14
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

可以尝试一下以下tcp连接方法:

执行顺序为init->startTcpSocketConnect->sendMessage->tcpSocketRelease 如果需要绑定,则绑定IP需要再同一网络下。

import socket from '@ohos.net.socket';
import connection from '@ohos.net.connection';
import { BusinessError, ErrorCallback, systemDateTime } from '@kit.BasicServicesKit';
import buffer from '@ohos.buffer';

const CONNECT_TIMEOUT: number = 10000;

//tcp连接对象
let tcpSocket: socket.TCPSocket = socket.constructTCPSocketInstance();

//连接服务器的地址和端口
let connectAddress: socket.NetAddress = {
  address: 'localhost',
  family: 1,
  port: 8838
}

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

export class SocketDemo {
  constructor() {
  }

  /**
   * tcp连接状态和消息监听
   */
  private setTcpSocketListener() {
    tcpSocket.on('connect', () => {
      this.log("tcp回调  tcp通道已连接");
      this.setOptions();
    })

    tcpSocket.on('message', (value: SocketInfo) => {
      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("on connect received:" + str);
    });

    tcpSocket.on('close', () => {
      this.log("tcp回调  close监听:关闭连接")
    })
  }

  /**
   * 必须上线后设置
   * */
  private setOptions() {
    let tcpExtraOptions: socket.TCPExtraOptions = {
      keepAlive: true, //是否保持连接。默认为false
      OOBInline: false, //是否为OOB内联。默认为false
      TCPNoDelay: true, //TCPSocket连接是否无时延。默认为false
      socketLinger: {
        on: true,
        linger: 10000
      }, //socket是否继续逗留。- on:是否逗留(true:逗留;false:不逗留)。- linger:逗留时长,单位毫秒(ms),取值范围为0~65535。当入参on设置为true时,才需要设置。
      receiveBufferSize: 4096, //接收缓冲区大小(单位:Byte),默认为0
      sendBufferSize: 4096, //发送缓冲区大小(单位:Byte),默认为0。
      reuseAddress: true, //是否重用地址。默认为false。
      socketTimeout: 30000 //套接字超时时间,单位毫秒(ms),默认为0。
    }


    // {"code":2301009,"message":"Bad file descriptor"}
    tcpSocket.setExtraOptions(tcpExtraOptions, (err: BusinessError) => {
      this.log('setExtraOptions error:' + JSON.stringify(err));
      if (err) {
        this.log('  setExtraOptions 失败');
        return;
      }
      this.log(' setExtraOptions 成功');
    });
  }

  /**
   * 发送消息数据
   * @param message
   */
  public sendMessage() {
    // 发送数据
    tcpSocket.getState().then((data) => {
      //已连接
      if (data.isConnected) {
        //发送消息
        tcpSocket.send({ data: 'Hello' })
          .then(() => {
            this.log("消息发送成功 回执");
          })
          .catch((error: BusinessError) => {
            this.log(" 消息发送失败,原因:" + JSON.stringify(error));
          })
      } else {
        this.log("没有连接");
      }
    })
  }

  /**
   * 连接服务器
   */
  public startTcpSocketConnect() {
    //开始连接
    let tcpConnect: socket.TCPConnectOptions = {} as socket.TCPConnectOptions;
    tcpConnect.address = connectAddress;
    tcpConnect.timeout = CONNECT_TIMEOUT;

    this.log('tcpSocket.connect info:' + JSON.stringify(tcpConnect));

    tcpSocket.connect(tcpConnect, (err: BusinessError) => {
      // {"code":2301115,"message":"Operation in progress"}
      this.log('tcpSocket.connect error:' + JSON.stringify(err));
      if (err) {
        this.log('连接服务器失败');
        return;
      }
      this.log('连接服务器成功,准备执行上线操作');
    });
  }

  public init() {
    this.setTcpSocketListener();
  }

  /**
   * 关闭Socket监听和连接,释放资源
   */
  public tcpSocketRelease() {
    tcpSocket.off("message")
    tcpSocket.off("connect")
    tcpSocket.off("close")
    tcpSocket.close()
  }

  private log(message: string) {
    console.log(message)
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
分享
微博
QQ
微信
回复
2024-12-27 19:50:35
相关问题
HarmonyOS socket tcp连接报错
931浏览 • 1回复 待解决
HarmonyOS Tcp socket问题
972浏览 • 1回复 待解决
HarmonyOS TCP连接粘包处理
631浏览 • 1回复 待解决
HarmonyOS Mqtt无法Connect成功
1007浏览 • 1回复 待解决
关于Tcp 5037一直连接不上问题
7375浏览 • 1回复 待解决
ArkUI 支持 Tcp Server吗?
4019浏览 • 1回复 待解决
支付成功没有收到回调?
2652浏览 • 1回复 待解决