C# 中实现不同程序进程间消息交互

使用管道Pipe方式实现:限于同一台主机下不同程序之间的数据交互

服务端实现:

private void StartPipe()
{
    var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 5, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
    ThreadPool.QueueUserWorkItem(delegate
    {
        pipeServer.BeginWaitForConnection(async (o) =>
        {
            NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState;
            pServer.EndWaitForConnection(o);
            StreamReader sr = new StreamReader(pServer);
            while (true)
            {
                string message = await sr.ReadLineAsync();
                if (message != null)
                {
                    this.Invoke(new Action(() => GetClientMessage(message)));
                    //(MethodInvoker)delegate { selectPuller.SelectedValue = new SelectItem(message); };
                    this.Invoke((MethodInvoker)delegate
                    {
                        selectPuller.SelectedValue = new SelectItem(message);
                    });
                }
            }
        }, pipeServer);
    });
}


private void GetClientMessage(string message)
{
    Console.WriteLine($"收到Client管道信息:{message}");
}

客户端:

 static NamedPipeClientStream pipeClient =
 new NamedPipeClientStream(".", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None);
 StreamWriter sw = null;
 //连接服务端
 private void ConnectPipe()
 {
     try
     {
         pipeClient.Connect(5000);
         sw = new StreamWriter(pipeClient);
         sw.AutoFlush = true;
     }
     catch (Exception ex)
     {
         MessageBox.Show("连接建立失败,请确保服务端程序已经被打开。");
         this.Close();
     }
 }

//消息发送,在winfrom页面中输入
private void btnPipe_Click(object sender, EventArgs e)
{
    if (sw != null && pipeClient.IsConnected)
    {
        if (!pipeClient.IsConnected) {
            pipeClient.Connect(5000);
            sw = new StreamWriter(pipeClient);
            sw.AutoFlush = true;
        }
        sw.WriteLine(this.txtPipeMsg.Text);
    }
    else
    {
        MessageBox.Show("未建立连接,不能发送消息。");
    }
}

你可能感兴趣的:(Winform,C#基础,.net,core,c#,交互,服务器)