天天看點

C#中使用命名管道進行程序通信的執行個體

1 建立解決方案NamedPipeExample

在解決方案下面建立兩個項目:Client和Server,兩者的輸出類型均為“Windows 應用程式”。整個程式的結構如下圖所示。

C#中使用命名管道進行程式通信的執行個體

2 實作項目Client

Client僅包含一個名為“用戶端”的窗體,如下圖所示。

C#中使用命名管道進行程式通信的執行個體

編寫窗體後端代碼,如下所示。

using System;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Windows.Forms;
 
namespace Client
{
    public partial class frmClient : Form
    {
        NamedPipeClientStream pipeClient =
            new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None);
        StreamWriter sw = null;
 
        public frmClient()
        {
            InitializeComponent();
        }
 
        private void frmClient_Load(object sender, EventArgs e)
        {
            try
            {
                pipeClient.Connect(5000);
                sw = new StreamWriter(pipeClient);
                sw.AutoFlush = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("連接配接建立失敗,請確定服務端程式已經被打開。");
                this.Close();
            }
        }
 
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (sw != null)
            {
                sw.WriteLine(this.txtMessage.Text);
            }
            else
            {
                MessageBox.Show("未建立連接配接,不能發送消息。");
            }
        }
    }
}
           

3 實作項目Server

Server項目僅包含一個名為“服務端”的窗體,如下圖所示。

C#中使用命名管道進行程式通信的執行個體

編寫窗體後端代碼,如下所示。

using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Windows.Forms;
 
namespace Server
{
    public partial class frmServer : Form
    {
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut,1,PipeTransmissionMode.Message,PipeOptions.Asynchronous);
        public frmServer()
        {
            InitializeComponent();
        }
 
        private void frmServer_Load(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                pipeServer.BeginWaitForConnection((o) => 
                {
                    NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState;
                    pServer.EndWaitForConnection(o);
                    StreamReader sr = new StreamReader(pServer);
                    while (true)
                    {
                        this.Invoke((MethodInvoker)delegate { lsvMessage.Items.Add(sr.ReadLine()); });
                    }
                }, pipeServer);
            });
        }
    }
}
 
           

4 運作程式

運作Server.exe與Client.exe程式,效果如下圖所示。

C#中使用命名管道進行程式通信的執行個體

執行個體中共發送三次消息,分别傳遞資料1,2,3。

本例中示範的用戶端和服務端程式均位于本地機器,使用命名管道可以與網絡上的其他程序進行通信。