Just for fun——C#應用和Nodejs通信

進程通訊

常見的進程通信的方法有:html

  • 管道(Pipe)
  • 命名管道
  • 信號
  • 消息隊列
  • 其餘

管道是比較簡單基礎的技術了,因此看看它。node

Node IPC支持

Node官方文檔中Net模塊寫着:api

IPC Support

The net module supports IPC with named pipes on Windows,
and UNIX domain sockets on other operating systems.dom

Class: net.Server

Added in: v0.1.90 This class is used to create a TCP or IPC server.socket

能夠看到,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);
                }
            }
        }
    }
}

設計界面很簡單:ui

clipboard.png

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');
});

代碼很簡單,建立一個鏈接,而後發送數據。spa

測試效果

clipboard.png

總結

多看文檔哦^_^
C#代碼下載設計

相關文章
相關標籤/搜索