目录
写在前面
使用 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."