进程通信
常见的进程通讯的方法有:
管道 (Pipe)
命名管道
信号
消息队列
其他
管道是比较简单基础的技术了, 所以看看它
Node IPC 支持
Node 官方文档中 Net 模块写着:
- IPC Support
- The net module supports IPC with named pipes on Windows,
- and UNIX domain sockets on other operating systems.
- Class: net.Server
- Added in: v0.1.90 This class is used to create a TCP or IPC server.
可以看到, Node 在 Windows 上可以用命名管道进行进程通信
测试
- C#
- public partial class frmMain : Form
- {
- public frmMain()
- {
- InitializeComponent();
- }
- private const string PIPE_NAME = "salamander_pipe";
- private void btnStartListen_Click(object sender, EventArgs e)
- {
- Task.Factory.StartNew(StartListen);
- }
- private void StartListen()
- {
- for (;;)
- {
- using (NamedPipeServerStream pipeServer =
- new NamedPipeServerStream(PIPE_NAME, PipeDirection.InOut, 1))
- {
- try
- {
- pipeServer.WaitForConnection();
- pipeServer.ReadMode = PipeTransmissionMode.Byte;
- using (StreamReader sr = new StreamReader(pipeServer))
- {
- string message = sr.ReadToEnd();
- txtMessage.Invoke(new EventHandler(delegate
- {
- txtMessage.AppendText(message + "\n");
- }));
- }
- }
- catch (IOException ex)
- {
- MessageBox.Show("监听管道失败:" + ex.Message);
- }
- }
- }
- }
- }
设计界面很简单:
- Nodejs
- const net = require('net');
- const PIPE_NAME = "salamander_pipe";
- const PIPE_PATH = "\\\\.\\pipe\\" + PIPE_NAME;
- let l = console.log;
- const client = net.createConnection(PIPE_PATH, () => {
- //'connect' listener
- l('connected to server!');
- client.write('world!\r\n');
- client.end();
- });
- client.on('end', () => {
- l('disconnected from server');
- });
代码很简单, 创建一个连接, 然后发送数据
测试效果
来源: https://segmentfault.com/a/1190000013341168