HarmonyOS 鸿蒙Next socket Tcp连接消息问题

发布于 1周前 作者 yuanlaile 来自 鸿蒙OS

HarmonyOS 鸿蒙Next socket Tcp连接消息问题 socket Tcp连接 connect 成功后无法收到tcp.on(‘message’)的消息

2 回复

你可以尝试一下以下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)
  }
}

更多关于HarmonyOS 鸿蒙Next socket Tcp连接消息问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


针对HarmonyOS(鸿蒙)系统中Next socket Tcp连接消息问题,以下是一些可能的解决方案和考虑因素:

在鸿蒙系统中,TCP连接的消息处理通常涉及网络编程的基本概念,如socket编程、TCP/IP协议栈等。如果遇到Next socket Tcp连接消息问题,可能的原因包括但不限于:

  1. 网络配置错误:检查设备的网络配置,确保IP地址、子网掩码、网关等设置正确无误。同时,确认服务器端和客户端的网络环境是否互通。

  2. 端口占用或冲突:确认所使用的TCP端口未被其他应用占用,且服务器端和客户端的端口号一致。

  3. 防火墙或安全策略:检查设备的防火墙设置或安全策略,确保TCP连接未被阻止。

  4. 数据格式或协议问题:确保客户端和服务器端在数据格式、协议等方面保持一致,以避免因格式不匹配导致的连接问题。

  5. 系统资源限制:检查系统资源使用情况,如文件描述符数量、内存占用等,确保系统资源充足以支持TCP连接。

如果上述方法均无法解决问题,可能需要进一步检查应用程序的代码实现,或考虑是否存在系统级的bug。在排查过程中,可以使用网络抓包工具(如Wireshark)来捕获和分析TCP连接过程中的数据包,以便更准确地定位问题。

如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!