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

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

HarmonyOS
6天前
浏览
收藏 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%')
  }
}

客户端代码: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%')
  }
}
分享
微博
QQ
微信
回复
6天前
相关问题
公共事件实现跨进程通信
944浏览 • 1回复 待解决
HarmonyOS preference支持跨进程读写吗?
239浏览 • 1回复 待解决
如何跨进程调用其他应用的服务
1759浏览 • 1回复 待解决
HarmonyOS 经典蓝牙的socket通信问题
465浏览 • 1回复 待解决
IPC跨进程通讯是否能够异步返回数据
453浏览 • 1回复 待解决
HarmonyOS能否监听到设备翻转
482浏览 • 1回复 待解决