HarmonyOS 能否通过Socket 监听127.0.0.1实现跨进程通信

我们能否使用Socket 监听 127.0.0.1进行跨进程通信,在按照官方文件测试过程中发现无法联通,请问这种方案是否可行,如果可行能否提供一个测试demo

HarmonyOS
2024-12-27 18:23:29
961浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

可以参考以下代码:

服务端代码:ServerSocketPage.ets

import socket from '@ohos.net.socket';
import { BusinessError } from '@ohos.base';
// 创建一个TCPSocketServer连接,返回一个TCPSocketServer对象。
let tcpServer = socket.constructTCPSocketServerInstance();
// 绑定本地IP地址和端口,进行监听

let ipAddress : socket.NetAddress = {} as socket.NetAddress;
let socketClient: socket.TCPSocketConnection
ipAddress.address = "127.0.0.1";
ipAddress.port = 4651;


class SocketInfo {
  message: ArrayBuffer = new ArrayBuffer(1);
  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
}


// 取消TCPSocketServer相关的事件订阅
setTimeout(() => {
  tcpServer.off("connect");
}, 30 * 1000);
@Entry
@Component
struct ServerSocketPage {
  build() {
    Row() {
      Column() {
        Button("connect init")
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(()=> {
            tcpServer.listen(ipAddress, (err: BusinessError) => {
              if (err) {
                console.log("listen fail");
                return;
              }
              console.log("listen success");

              // 订阅TCPSocketServer的connect事件
              tcpServer.on("connect", (client: socket.TCPSocketConnection) => {
                console.log("tcp socket server connect success");
                // 订阅TCPSocketConnection相关的事件
                socketClient=client
                socketClient.on("close", () => {
                  console.log("on close success");
                });
                socketClient.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("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);
                });

              });
            });

          })
        Button("send")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=> {
            // 向客户端发送数据
            let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions;
            tcpSendOptions.data = 'Hello, client!';
            socketClient.send(tcpSendOptions, (err: BusinessError) => {
              if (err) {
                console.log("send fail");
                return;
              }
              console.log("send success");
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 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.

客户端代码:ClientSocketPage.ets

import socket from '@ohos.net.socket';
import { BusinessError } from '@ohos.base';

class SocketInfo {
  message: ArrayBuffer = new ArrayBuffer(1);
  remoteInfo: socket.SocketRemoteInfo = {} as socket.SocketRemoteInfo;
}
// 创建一个TCPSocket连接,返回一个TCPSocket对象。
let tcp = socket.constructTCPSocketInstance();


// 绑定本地IP地址和端口。
let ipAddress : socket.NetAddress = {} as socket.NetAddress;
ipAddress.address = "127.0.0.1";
ipAddress.port = 1234;


// 连接使用完毕后,主动关闭。取消相关事件的订阅。
setTimeout(() => {
  tcp.close((err: BusinessError) => {
    console.log('close socket.');
  });
  tcp.off('message');
  tcp.off('connect');
  tcp.off('close');
}, 30 * 1000);
@Entry
@Component
struct ClientSocketPage {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {

        Button("connect server")
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            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");
            });

            tcp.bind(ipAddress, (err: BusinessError) => {
              if (err) {
                console.log('bind fail');
                return;
              }
              console.log('bind success');

              // 连接到指定的IP地址和端口。
              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');

              });

            });

          })
        Button("send")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            // 发送数据
            let tcpSendOptions : socket.TCPSendOptions = {} as socket.TCPSendOptions;
            tcpSendOptions.data = 'Hello, server!';
            tcp.send(tcpSendOptions, (err: BusinessError) => {
              if (err) {
                console.log('send fail');
                return;
              }
              console.log('send success');
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-12-27 19:59:03


相关问题
公共事件实现跨进程通信
1645浏览 • 1回复 待解决
内存泄漏的跨进程追踪
349浏览 • 0回复 待解决
HarmonyOS preference支持跨进程读写吗?
844浏览 • 1回复 待解决
HarmonyOS 经典蓝牙的socket通信问题
1302浏览 • 1回复 待解决
如何跨进程调用其他应用的服务
2426浏览 • 1回复 待解决
HarmonyOS 如何监听蓝牙socket断开
681浏览 • 1回复 待解决
IPC跨进程通讯是否能够异步返回数据
1050浏览 • 1回复 待解决