首页  ·  知识 ·  编程语言
命名管道实现服务器与客户端的通信
网友    .NET  编辑:dezai   图片来源:网络
命名管道提供的功能比匿名管道多。其功能包括通过网络进行全双工通信和多个服务器实例;基于消息的通信;以及客户端模拟,这使得连接进程可在远程服务器上使用其自己的权限
 示例:

服务端代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.IO;

using System.IO.Pipes;

namespace Servier

{

    class Program

    {

        static void Main(string[] args)

        {

            NamedPipeServerStream serverPipe = new NamedPipeServerStream("server",

                PipeDirection.InOut,5); 

                wite:serverPipe.WaitForConnection();

            

            Console.WriteLine("连接上了");

            byte[] msgbutes=new byte[256];

            int readCount = 0;

            while ((readCount = serverPipe.Read(msgbutes, 0, 256)) > 0)

            {

                string msg = Encoding.UTF8.GetString(msgbutes, 0, readCount);

                if (msg == "exit")

                    break;

                Console.WriteLine(msg);

            }

            Console.WriteLine("退出了,等下一个连接......");

            //serverPipe.Close();

            serverPipe.Disconnect();

            goto wite;

            

        }

    }

}

 

客户端代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.IO.Pipes;

namespace client

{

    class Program

    {

        static void Main(string[] args)

        {

            NamedPipeClientStream clientPipe = new NamedPipeClientStream(".",

                "server", PipeDirection.InOut);

            clientPipe.Connect();

            

            string msg = "";

            while ((msg=Console.ReadLine()) != "")

            {

                byte[] buffer = Encoding.UTF8.GetBytes(msg);

                clientPipe.Write(buffer, 0, buffer.Length);

            }

 

           clientPipe.Close();

        }

    }

}

 
本文作者:网友 来源:网络
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读