nodejs 管道通讯

概述

2个nodejs程序的一种通讯方式,管道通讯,跟其他语言一样,管道通讯是一种特殊的socket通讯,普通的socket通讯是通过监听端口触发通讯机制,管道通讯是通过监听文件的方式进行通讯,一般用于单机的多进程通讯,这里演示的是2个node的进程间管道通讯,也可以是node跟其他语言生成的程序进行通讯,例如服务端是node的程序,客户端是exe程序,这样可以实现exe和node间的通讯。

直接上demo吧

服务端

const net = require('net');
let path = require('path');
let server = net.createServer(function (connect) {
  //connect.setEncoding('binary');
  connect.on('error', function (exception) {
    console.log('socket error:' + exception);
    connect.end();
  });
  //客户端关闭事件
  connect.on('close', function (data) {
    console.log('client closed!');
  });
  connect.on("data", function (data) {
    //server接受到client发送的数据
    console.log("接收到:" + data);
    //server给client发送数据	
    connect.write("你好");
  })
}).listen(
  path.join('\\\\?\\pipe', '\\getAppListDesktop'));
server.on("error", function (exception) {
  console.log("server error:" + exception);
});

客户端


let net = require('net');
let path = require('path');
let client = new net.Socket();
//client.setEncoding('binary');
client.connect(path.join('\\\\?\\pipe', '\\getAppListDesktop'), function () {
  //client给server发送数据
  client.write("你好,我是来自客户端");
});
client.on('data', function (data) {
  console.log("收到服务端消息: " + data);
  //此处接受到数据后就可以进行合适的处理了
  //client.end();
});
client.on('close', function () {
  console.log('Connection closed');
});
client.on('error', function (error) {
  console.log('error:' + error);
  client.destory();
})

运行方式

使用node 启动服务端

再使用node 启动客户端

相关推荐

  1. 通过 nvm 管理 Node 版本

    2023-12-17 05:56:03       44 阅读
  2. 进程间通讯-管道

    2023-12-17 05:56:03       34 阅读
  3. Nodejs版本管理工具nvm

    2023-12-17 05:56:03       18 阅读
  4. Node版本管理 - nvm

    2023-12-17 05:56:03       40 阅读
  5. <span style='color:red;'>nodejs</span>

    nodejs

    2023-12-17 05:56:03      14 阅读
  6. <span style='color:red;'>nodejs</span>

    nodejs

    2023-12-17 05:56:03      10 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-17 05:56:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-17 05:56:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-17 05:56:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-17 05:56:03       18 阅读

热门阅读

  1. Next.js 学习笔记(二)——项目结构

    2023-12-17 05:56:03       39 阅读
  2. ntp时间同步配置中 server、pool和peer的区别

    2023-12-17 05:56:03       39 阅读
  3. 分布式配置中心SpringCloudConfig

    2023-12-17 05:56:03       40 阅读
  4. Python 正则表达式模块:re 模块

    2023-12-17 05:56:03       43 阅读
  5. C语言之实现贪吃蛇小游戏篇

    2023-12-17 05:56:03       35 阅读
  6. 固态硬盘缓存和不缓存的区别

    2023-12-17 05:56:03       39 阅读
  7. Spring Boot 默认缓存

    2023-12-17 05:56:03       29 阅读
  8. 百度搜索品牌形象优化怎么做?

    2023-12-17 05:56:03       38 阅读
  9. leetcode 股票问题全序列

    2023-12-17 05:56:03       45 阅读
  10. spark-常用算子

    2023-12-17 05:56:03       28 阅读