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; 
} 
  • 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.
  • 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); 
  
}
  • 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.

实现效果

注明适配的版本信息

IDE版本:4.1.3.500

SDK版本:HarmonyOS Next Developer Preview1

分享
微博
QQ
微信
回复
2024-05-29 21:35:49
相关问题
ArkUI 支持 Tcp Server吗?
3777浏览 • 1回复 待解决
HarmonyOS Tcp socket问题
745浏览 • 1回复 待解决
HarmonyOS socket tcp连接报错
753浏览 • 1回复 待解决
HarmonyOS 经典蓝牙的socket通信问题
1058浏览 • 1回复 待解决
鸿蒙是否进行异步通信
4550浏览 • 1回复 待解决
前端页面原生页面如何进行通信
1178浏览 • 1回复 待解决
HarmonyOS TCP连接粘包处理
452浏览 • 1回复 待解决
nginx tcp转发 怎么获取源IP?
3273浏览 • 1回复 待解决
fegin docker 通信问题
3314浏览 • 1回复 待解决
如何使用arkts进行http请求通信
33浏览 • 0回复 待解决