进程通信
常见的进程通讯的方法有:
- 管道(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');
});
代码很简单,创建一个连接,然后发送数据。
测试效果
总结
多看文档哦^_^
C#代码下载
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。