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

HarmonyOS
6天前
浏览
收藏 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)
  }
}
分享
微博
QQ
微信
回复
6天前
相关问题
HarmonyOS socket tcp连接报错
174浏览 • 1回复 待解决
HarmonyOS Tcp socket问题
173浏览 • 1回复 待解决
HarmonyOS TCP连接粘包处理
51浏览 • 1回复 待解决
HarmonyOS Mqtt无法Connect成功
89浏览 • 1回复 待解决
关于Tcp 5037一直连接不上问题
6679浏览 • 1回复 待解决
支付成功没有收到回调?
1886浏览 • 1回复 待解决
ArkUI 支持 Tcp Server吗?
3435浏览 • 1回复 待解决