C# 命名管道进行进程通信--pipe通讯

C#中使用命名管道进行进程通信的实例
原文: C#中使用命名管道进行进程通信的实例
1 新建解决方案NamedPipeExample

在解决方案下面新建两个项目:Client和Server,两者的输出类型均为“Windows 应用程序”。整个程序的结构如下图所示。

在这里插入图片描述

2 实现项目Client

Client仅包含一个名为“客户端”的窗体,如下图所示。
在这里插入图片描述

编写窗体后端代码,如下所示。

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项目仅包含一个名为“服务端”的窗体,如下图所示。

在这里插入图片描述

编写窗体后端代码,如下所示。

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程序,效果如下图所示。

在这里插入图片描述

实例中共发送三次消息,分别传递数据1,2,3。

本例中演示的客户端和服务端程序均位于本地机器,使用命名管道可以与网络上的其他进程进行通信。

posted on 2015-11-20 23:26 NET未来之路 阅读(…) 评论(…) 编辑 收藏
转载于:https://www.cnblogs.com/lonelyxmas/p/4982641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Seven Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值