命名管道跨进程通信实例2(转)

原文:http://www.cnblogs.com/jonneydong/archive/2012/03/02/2418743.html

服务端代码:

//创建服务端,管道实例
NamedPipeServerStream serverStream = new NamedPipeServerStream("test2PIPE",
    PipeDirection.InOut,
    1,
    PipeTransmissionMode.Message,
    PipeOptions.Asynchronous);
private void Form1_Load(object sender, EventArgs e)
{
    //启用线程接收消息
    ThreadPool.QueueUserWorkItem(delegate
    {
        serverStream.BeginWaitForConnection((o) =>
        {
            NamedPipeServerStream server = (NamedPipeServerStream)o.AsyncState;
            server.EndWaitForConnection(o);
            StreamReader sr = new StreamReader(server);
            StreamWriter sw = new StreamWriter(server);
            string result = null;
            string clientName = server.GetImpersonationUserName();
            while (true)
            {
                result = sr.ReadLine();
                if (result == null || result == "bye")
                    break;
                this.Invoke((MethodInvoker)delegate
                {
                    listBox1.Items.Add(clientName + ":" + result);
                });
            }
        }, serverStream);
    });

}

客户端代码:

        //创建客户端连接实例
        NamedPipeClientStream clientStream = new NamedPipeClientStream("127.0.0.1",
            "test2PIPE",
            PipeDirection.InOut, PipeOptions.Asynchronous,
            System.Security.Principal.TokenImpersonationLevel.None
            );
        StreamWriter sw = null;
        private void Form1_Load(object sender, EventArgs e)
        {
            //连接管道
            clientStream.Connect();
            sw = new StreamWriter(clientStream);
            sw.AutoFlush = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //向管道中写入内容
            sw.WriteLine(richTextBox1.Text);
        }

显示结果:

经发现,命名管道, 其实是基于TCP/IP 来连接. 且端口为 445

当然, 我这里只是 传输一个字符串做为信息而已.! 其实仍然 可以传输自己所定义的 对象 等.(记得序列化哟..)

posted @ 2015-12-23 15:20  天马3798  阅读(435)  评论(0编辑  收藏  举报