在HarmonyOS鸿蒙Next的Hypium测试框架中如何执行socket之类的服务啊

在HarmonyOS鸿蒙Next的Hypium测试框架中如何执行socket之类的服务啊 我在测试文件中添加的socket连接,但是执行的时候,根本没有打印内容,但是我用debug模式看了会走这些代码

3 回复

参考一下以下tcp连接方法:

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

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的Hypium测试框架中如何执行socket之类的服务啊的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next的Hypium测试框架中执行Socket服务,可以通过使用ArkTS语言编写测试用例来实现。Hypium测试框架支持ArkTS,ArkTS是HarmonyOS的推荐开发语言,基于TypeScript扩展而来。

首先,确保你的开发环境已经配置好HarmonyOS SDK和ArkTS编译器。然后,可以按照以下步骤进行操作:

  1. 创建测试模块:在工程中创建一个新的ArkTS测试模块,用于编写Socket相关的测试用例。

  2. 导入必要的模块:在ArkTS文件中导入@ohos.net.socket模块,该模块提供了Socket相关的API。

  3. 编写测试用例:在测试模块中编写测试用例,使用@ohos.net.socket模块中的API来创建、连接、发送和接收数据。例如:

import { describe, it, expect } from '@hypium/hypium';
import socket from '@ohos.net.socket';

describe('SocketTest', () => {
    it('testSocketCommunication', async () => {
        const tcpSocket = socket.constructTCPSocketInstance();
        await tcpSocket.connect({ address: '192.168.1.100', port: 8080 });
        await tcpSocket.send({ data: 'Hello, Server!' });
        const response = await tcpSocket.recv();
        expect(response).toEqual('Hello, Client!');
        await tcpSocket.close();
    });
});
  1. 运行测试:使用Hypium测试框架运行你编写的测试用例,验证Socket通信是否正常。

通过以上步骤,你可以在Hypium测试框架中执行Socket服务相关的测试。

在HarmonyOS鸿蒙Next的Hypium测试框架中执行Socket服务,可以通过以下步骤实现:

  1. 创建Socket对象:使用Java或C++的Socket API创建客户端或服务器端Socket对象。
  2. 配置连接:设置IP地址和端口号,建立连接。
  3. 数据传输:通过send()receive()方法进行数据发送和接收。
  4. 关闭连接:使用close()方法释放资源。

在Hypium测试框架中,你可以将这些操作封装在测试用例中,使用@Test注解标记测试方法,并通过assert语句验证预期结果。

例如:

@Test
public void testSocketCommunication() {
    Socket socket = new Socket("127.0.0.1", 8080);
    OutputStream out = socket.getOutputStream();
    out.write("Hello, Server!".getBytes());
    InputStream in = socket.getInputStream();
    byte[] buffer = new byte[1024];
    int len = in.read(buffer);
    assertEquals("Hello, Client!", new String(buffer, 0, len));
    socket.close();
}

确保在测试完成后释放资源,避免资源泄漏。

回到顶部