C#应用和Nodejs通讯
进程通信
常见的进程通讯的方法有:
- 管道(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#代码下载
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/04/14 02:00