socket通信示例,创建tcp server和tcp client进行通信

创建tcp server和tcp client进行通信

HarmonyOS
2024-05-28 20:31:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
北风_小浦

使用的核心API

核心代码解释

  • tcp client
import socket from '@ohos.net.socket'; 
import { BusinessError } from '@ohos.base'; 
import { buffer } from '@kit.ArkTS'; 
  
const tcp = socket.constructTCPSocketInstance(); 
  
export function tpc_client(): void { 
  class SocketInfo { 
    message: ArrayBuffer = new ArrayBuffer(1); 
    remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 
  } 
  // Create a TCP socket connection. A TCPSocket object is returned. 
  // tcp = socket.constructTCPSocketInstance(); 
  tcp.on('message', (value: SocketInfo) => { 
    console.log("on message"); 
    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); 
  }); 
  tcp.on('connect', () => { 
    console.log("on connect"); 
  }); 
  tcp.on('close', () => { 
    console.log("on close"); 
  }); 
  
  // Bind the local IP address and port number. 
  let ipAddress : socket.NetAddress = {} as socket.NetAddress; 
  ipAddress.address = "127.0.0.1"; 
  ipAddress.port = 1234; 
  tcp.bind(ipAddress, (err: BusinessError) => { 
    if (err) { 
      console.log('bind fail'); 
      return; 
    } 
    console.log('bind success'); 
  
    // Set up a connection to the specified IP address and port number. 
    ipAddress.address = "127.0.0.1"; 
    ipAddress.port = 4651; 
  
    let tcpConnect : socket.TCPConnectOptions = {} as socket.TCPConnectOptions; 
    tcpConnect.address = ipAddress; 
    tcpConnect.timeout = 6000; 
  
    tcp.connect(tcpConnect, (err: BusinessError) => { 
      if (err) { 
        console.log('connect fail'); 
        return; 
      } 
      console.log('connect success'); 
      // Send data over the connection. 
      let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions; 
      let num: number = 0; 
      // tcpSendOptions.data = 'Hello, server:' + num; 
      // 发送buffer数据 
      let buffer = new ArrayBuffer(10); 
      let view = new Uint8Array(buffer); 
      view[0] = 100; 
      view[1] = 101; 
      tcpSendOptions.data = buffer; 
  
      // tcpSendOptions.data = stringToArrayBuffer('chisj'); 
      tcp.send(tcpSendOptions, (err: BusinessError) => { 
        if (err) { 
          console.log('1 send fail'); 
          return; 
        } 
        console.warn('chisj debug : client send 1 message success.') 
      }) 
      setInterval(() => { 
        num++; 
        tcpSendOptions.data = 'Hello, server:' + num; 
        tcp.send(tcpSendOptions, (err: BusinessError) => { 
          if (err) { 
            console.log('send fail, num = ', num); 
            return; 
          } 
          console.warn('chisj debug : client send message success, num = ', num) 
          // console.log('2 send success'); 
        }) 
      }, 10 * 1000); 
    }); 
  }); 
  
  // Enable the socket connection to be automatically closed after use. Then, unsubscribe from events of the connection. 
  // setTimeout(() => { 
  //   tcp.close((err: BusinessError) => { 
  //     console.log('close socket.'); 
  //   }); 
  //   tcp.off('message'); 
  //   tcp.off('connect'); 
  //   tcp.off('close'); 
  // }, 60 * 1000); 
}; 
  
let index: number = 0; 
let clientSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions; 
  
export function sendMsg() { 
  index++; 
  clientSendOptions.data = 'client msg:' + index; 
  tcp.send(clientSendOptions, (err: BusinessError) => { 
    if (err) { 
      console.log('sendMsg fail, index = ', index); 
      return; 
    } 
    console.warn('chisj debug : client sendMsg success, index = ', index); 
  }) 
}; 
  
function stringToArrayBuffer(str: string): ArrayBuffer { 
  let uint8Array: Uint8Array = new Uint8Array(buffer.from(str).buffer) 
  return uint8Array.buffer; 
} 
  • tcp server
import socket from '@ohos.net.socket'; 
import { BusinessError } from '@ohos.base'; 
  
const tcpServer = socket.constructTCPSocketServerInstance(); 
let gClient:socket.TCPSocketConnection; 
let tcpConnectArray: socket.TCPSocketConnection[] = []; 
export function create_server(): void { 
  // Create a TCP socket server connection. A TCPSocketServer object is returned. 
  
  // Bind the local IP address and port number for listening. 
  let ipAddress : socket.NetAddress = {} as socket.NetAddress; 
  ipAddress.address = "127.0.0.1"; 
  ipAddress.port = 4651; 
  tcpServer.listen(ipAddress, (err: BusinessError) => { 
    if (err) { 
      console.log("listen fail"); 
      return; 
    } 
    console.log("listen success"); 
  }); 
  
  class SocketInfo { 
    message: ArrayBuffer = new ArrayBuffer(1); 
    remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo; 
  } 
  // Subscribe to connect events of the TCPSocketServer object. 
  tcpServer.on("connect", (client: socket.TCPSocketConnection) => { 
    // gClient = client; 
    tcpConnectArray.push(client); 
    console.warn('chisj debug : client connect.', client.clientId) 
    // Subscribe to events of the TCPSocketConnection object. 
    client.on("close", () => { 
      console.log("on close success"); 
    }); 
    client.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.warn('chisj debug : received message = ', str); 
      console.log("received message--:" + str); 
      console.log("received address--:" + value.remoteInfo.address); 
      console.log("received family--:" + value.remoteInfo.family); 
      console.log("received port--:" + value.remoteInfo.port); 
      console.log("received size--:" + value.remoteInfo.size); 
    }); 
  
    // Send data to the client. 
    let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions; 
    tcpSendOptions.data = 'Hello, client!'; 
    client.send(tcpSendOptions, (err: BusinessError) => { 
      if (err) { 
        console.log("send fail"); 
        return; 
      } 
      console.log("send success"); 
    }); 
  
    // Close the connection between the client and the server. 
    // client.close((err: BusinessError) => { 
    //   if (err) { 
    //     console.log("close fail"); 
    //     return; 
    //   } 
    //   console.log("close success"); 
    // }); 
  
    // Unsubscribe from events of the TCPSocketConnection object. 
    // setTimeout(() => { 
    //   client.off("message"); 
    //   client.off("close"); 
    // }, 120 * 1000); 
  }); 
  
  // Unsubscribe from events of the TCPSocketServer object. 
  // setTimeout(() => { 
  //   tcpServer.off("connect"); 
  // }, 120 * 1000); 
  
}

实现效果

注明适配的版本信息

IDE版本:4.1.3.500

SDK版本:HarmonyOS Next Developer Preview1

分享
微博
QQ
微信
回复
2024-05-29 21:35:49
相关问题
ArkUI 支持 Tcp Server吗?
3280浏览 • 1回复 待解决
HarmonyOS 经典蓝牙的socket通信问题
258浏览 • 1回复 待解决
鸿蒙是否进行异步通信
3821浏览 • 1回复 待解决
前端页面原生页面如何进行通信
270浏览 • 1回复 待解决
fegin docker 通信问题
2620浏览 • 1回复 待解决
基于libuv异步库进行线程通信
1773浏览 • 0回复 待解决
TaskPool如何跟主线程进行通信
431浏览 • 1回复 待解决
HarmonyOS HAP之间如何进行通信
339浏览 • 1回复 待解决
请问HAP如何与HAR进行通信交流?
327浏览 • 1回复 待解决
HarmonyOS h5ArkTS通信
110浏览 • 1回复 待解决
nginx tcp转发 怎么获取源IP?
2797浏览 • 1回复 待解决
PolarDB 如何进行数据通信
2885浏览 • 1回复 待解决
TaskPool子线程主线程如何通信
2249浏览 • 1回复 待解决
fegin docker 通信问题有懂的吗?
2671浏览 • 1回复 待解决