C# 使用命名管道进行网络进程间通信

目录

写在前面

代码实现

服务端代码

客户端代码

调用示例


写在前面

使用 NamedPipeServerStream 和 NamedPipeClientStream 类,实现命名管道方式的网络通讯,支持跨网络和多个服务器实例的全双工通信、基于消息的通信以及客户端模拟;需要特别说明的是TokenImpersonationLevel 的四个枚举项,对应了 SecurityAnonymous、SecurityIdentification、SecurityImpersonation和SecurityDelegation,分别代表如下四种模拟的等级。

  • 匿名(Anonymous):无法获取有关客户端的标识信息,且无法模拟客户端;
  • 识别(Identification):可以获取有关客户端的信息(如安全标识符和特权),但是无法模拟客户端;
  • 模拟(Impersonation):可以在本地模拟客户端的安全上下文。,但无法在远程系统上模拟客户端;
  • 委托(Delegation):可以在本地和远程系统上模拟客户端的安全上下文。

不同的模拟等级具有不同的权限,当权限足够时服务端才能响应对应级别的操作请求。

代码实现

服务端代码

using System;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;

public class PipeServer
{
    private static int numThreads = 4;

    private static string token = "天王盖地虎,今晚打老虎";

    public static void Main()
    {
        int i;
        Thread?[] servers = new Thread[numThreads];

        Console.WriteLine("\n*** Named pipe server stream with impersonation example ***\n");
        Console.WriteLine("Waiting for client connect...\n");
        for (i = 0; i < numThreads; i++)
        {
            servers[i] = new Thread(ServerThread);
            servers[i]?.Start();
        }
        Thread.Sleep(250);
        while (i > 0)
        {
            for (int j = 0; j < numThreads; j++)
            {
                if (servers[j] != null)
                {
                    if (servers[j]!.Join(250))
                    {
                        Console.WriteLine("Server thread[{0}] finished.", servers[j]!.ManagedThreadId);
                        servers[j] = null;
                        i--;    // decrement the thread watch count
                    }
                }
            }
        }
        Console.WriteLine("\nServer threads exhausted, exiting."
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值