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

news2024/9/22 17:36:47

目录

写在前面

代码实现

服务端代码

客户端代码

调用示例


写在前面

使用 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.");
    }

    private static void ServerThread(object? data)
    {
        var pipeServer = new NamedPipeServerStream("test.named.pipe", PipeDirection.InOut, numThreads);
        var threadId = Thread.CurrentThread.ManagedThreadId;

        // Wait for a client to connect
        pipeServer.WaitForConnection();

        Console.WriteLine("Client connected on thread[{0}].", threadId);
        try
        {
            // Read the request from the client. Once the client has
            // written to the pipe its security token will be available.

            StreamString ss = new StreamString(pipeServer);

            // Verify our identity to the connected client using a
            // string that the client anticipates.

            ss.WriteString(token); //对暗号
            string filename = ss.ReadString();

            // Read in the contents of the file while impersonating the client.
            ReadFileToStream fileReader = new ReadFileToStream(ss, filename);

            // Display the name of the user we are impersonating.
            Console.WriteLine("Reading file: {0} on thread[{1}] as user: {2}.",
                filename, threadId, pipeServer.GetImpersonationUserName());
            pipeServer.RunAsClient(fileReader.Start);
        }
        // Catch the IOException that is raised if the pipe is broken
        // or disconnected.
        catch (IOException e)
        {
            Console.WriteLine("ERROR: {0}", e.Message);
        }
        pipeServer.Close();
    }
}

// Defines the data protocol for reading and writing strings on our stream
public class StreamString
{
    private Stream ioStream;
    private UnicodeEncoding streamEncoding;

    public StreamString(Stream ioStream)
    {
        this.ioStream = ioStream;
        streamEncoding = new UnicodeEncoding();
    }

    public string ReadString()
    {
        int len = ioStream.ReadByte() * 256;
        len += ioStream.ReadByte();
        byte[] inBuffer = new byte[len];
        ioStream.Read(inBuffer, 0, len);

        return streamEncoding.GetString(inBuffer);
    }

    public int WriteString(string outString)
    {
        byte[] outBuffer = streamEncoding.GetBytes(outString);
        int len = outBuffer.Length;
        if (len > UInt16.MaxValue)
        {
            len = (int)UInt16.MaxValue;
        }
        ioStream.WriteByte((byte)(len / 256));
        ioStream.WriteByte((byte)(len & 255));
        ioStream.Write(outBuffer, 0, len);
        ioStream.Flush();

        // 加上了包头,就是上面写入的定义内容长度的两个字节,所以长度加2
        return outBuffer.Length + 2;
    }
}

// Contains the method executed in the context of the impersonated user
public class ReadFileToStream
{
    private string fn;
    private StreamString ss;

    public ReadFileToStream(StreamString str, string filename)
    {
        fn = filename;
        ss = str;
    }

    public void Start()
    {
        string contents = File.ReadAllText(fn);
        ss.WriteString(contents);
    }
}

客户端代码

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
using System.Text;
using System.Threading;

public class PipeClient
{
    private static int numClients = 4;

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


    public static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            if (args[0] == "spawnclient")
            {
                var pipeClient = new NamedPipeClientStream("127.0.0.1", "test.named.pipe",
                        PipeDirection.InOut, PipeOptions.None,
                        TokenImpersonationLevel.Impersonation);

                Console.WriteLine("Connecting to server...\n");
                pipeClient.Connect();

                var ss = new StreamString(pipeClient);
                // Validate the server's signature string.
                if (ss.ReadString() == token) //对暗号
                {
                    // The client security token is sent with the first write.
                    // Send the name of the file whose contents are returned
                    // by the server.
                    ss.WriteString("E:\\projects\\test_response.txt");

                    // Print the file to the screen.
                    Console.Write(ss.ReadString());
                }
                else
                {
                    Console.WriteLine("Server could not be verified.");
                }
                pipeClient.Close();
                // Give the client process some time to display results before exiting.
                Thread.Sleep(4000);
                Console.ReadLine();
            }
        }
        else
        {
            Console.WriteLine("\n*** Named pipe client stream with impersonation example ***\n");
            StartClients();
        }
    }

    // Helper function to create pipe client processes
    private static void StartClients()
    {
        string currentProcessName = Environment.CommandLine;

        // Remove extra characters when launched from Visual Studio
        currentProcessName = currentProcessName.Trim('"', ' ');

        currentProcessName = Path.ChangeExtension(currentProcessName, ".exe");
        Process?[] plist = new Process?[numClients];

        Console.WriteLine("Spawning client processes...\n");

        if (currentProcessName.Contains(Environment.CurrentDirectory))
        {
            currentProcessName = currentProcessName.Replace(Environment.CurrentDirectory, String.Empty);
        }

        // Remove extra characters when launched from Visual Studio
        currentProcessName = currentProcessName.Replace("\\", String.Empty);
        currentProcessName = currentProcessName.Replace("\"", String.Empty);

        int i;
        for (i = 0; i < numClients; i++)
        {
            // Start 'this' program but spawn a named pipe client.
            plist[i] = Process.Start(currentProcessName, "spawnclient");
        }
        while (i > 0)
        {
            for (int j = 0; j < numClients; j++)
            {
                if (plist[j] != null)
                {
                    if (plist[j]!.HasExited)
                    {
                        Console.WriteLine($"Client process[{plist[j]?.Id}] has exited.");
                        plist[j] = null;
                        i--;    // decrement the process watch count
                    }
                    else
                    {
                        Thread.Sleep(250);
                    }
                }
            }
        }
        Console.WriteLine("\nClient processes finished, exiting.");
    }
}

// Defines the data protocol for reading and writing strings on our stream.
public class StreamString
{
    private Stream ioStream;
    private UnicodeEncoding streamEncoding;

    public StreamString(Stream ioStream)
    {
        this.ioStream = ioStream;
        streamEncoding = new UnicodeEncoding();
    }

    public string ReadString()
    {
        int len = ioStream.ReadByte() * 256;
        len += ioStream.ReadByte();
        var inBuffer = new byte[len];
        ioStream.Read(inBuffer, 0, len);

        return streamEncoding.GetString(inBuffer);
    }

    public int WriteString(string outString)
    {
        byte[] outBuffer = streamEncoding.GetBytes(outString);
        int len = outBuffer.Length;
        if (len > UInt16.MaxValue)
        {
            len = (int)UInt16.MaxValue;
        }
        ioStream.WriteByte((byte)(len / 256));
        ioStream.WriteByte((byte)(len & 255));
        ioStream.Write(outBuffer, 0, len);
        ioStream.Flush();

        return outBuffer.Length + 2; // 加上了包头,就是上面写入的定义内容长度的两个字节,所以长度加2
    }
}

调用示例

服务端控制台输出: 

 客户端控制台输出:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1360919.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

力扣:15.三数之和

1.做题链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09; 2.做题前须&#xff1a; 两数之和降低复杂度&#xff1a; 1.问题描述&#xff1a;一个数组中找到两个数字之和是taeget 例如&#xff1a;[2,7,11,15,19,21],target30 2.解法一&#xff1a;暴力枚举时间复…

权威认可!甄知科技猪齿鱼产品荣获信创产品评估证书

近日&#xff0c;依据《信息技术应用创新产品评估规范 第1部分&#xff1a;应用软件》&#xff08;T/SSIA 2001-2022&#xff09;&#xff0c;经过严格评估&#xff0c;甄知科技旗下自主研发的猪齿鱼数智化开发管理平台 V2.0.0&#xff0c;通过信创测试认证&#xff0c;获得上海…

java基于SSM的毕业生就业管理系统+vue论文

摘 要 现代经济快节奏发展以及不断完善升级的信息化技术&#xff0c;让传统数据信息的管理升级为软件存储&#xff0c;归纳&#xff0c;集中处理数据信息的管理方式。本毕业生就业管理系统就是在这样的大环境下诞生&#xff0c;其可以帮助管理者在短时间内处理完毕庞大的数据信…

UE4运用C++和框架开发坦克大战教程笔记(十四)(第43~45集)

UE4运用C和框架开发坦克大战教程笔记&#xff08;十四&#xff09;&#xff08;第43~45集&#xff09; 43. 单个加载 UObject 功能获取资源 URL 链接实现异步加载单个 UObject 类型资源 44. 批量加载 UObject 功能测试加载单个 UObject 资源批量加载多个同类的 UObject 资源 45…

跟着小德学C++之日志记录

嗨&#xff0c;大家好&#xff0c;我是出生在达纳苏斯的一名德鲁伊&#xff0c;我是要立志成为海贼王&#xff0c;啊不&#xff0c;是立志成为科学家的德鲁伊。最近&#xff0c;我发现我们所处的世界是一个虚拟的世界&#xff0c;并由此开始&#xff0c;我展开了对我们这个世界…

VS2017 搭建opencv工程

VS2017 搭建opencv工程 opencv在处理图像方面具有很强的能力&#xff0c;在使用opencv之前先需要造好轮子。 1、opencv 官网 &#xff0c;下载对应的资源文件包。 根据自身选择。下载包之后&#xff0c;解压。分为build和sources source目录下分别存放&#xff1a; modules: …

Java面试项目推荐,异构数据源数据流转服务DatalinkX

前言 作为一个年迈的夹娃练习生&#xff0c;每次到了春招秋招面试实习生时都能看到一批简历&#xff0c;十个简历里得有七八个是写商城或者外卖项目。 不由得想到了我大四那会&#xff0c;由于没有啥项目经验&#xff0c;又想借一个质量高点的项目通过简历初筛&#xff0c;就…

Pytest的测试报告——Allure

一、html-report测试报告 html-report测试报告。是pytest下基本的测试报告。要使用pytest-html测试报告&#xff0c;就要确保python版本在3.6及以上即可。本身pytest所提供的测试结果汇总&#xff0c;是基于控制台的文本输出形式。 pytest-html是基于HTML格式实现的测试报告的…

三、C语言分支与循环知识点补充——随机数生成

本章分支结构的学习内容如下&#xff1a; 三、C语言中的分支与循环—if语句 (1) 三、C语言中的分支与循环—关系操作符 (2) 三、C语言中的分支与循环—条件操作符 与逻辑操作符(3) 三、C语言中的分支与循环—switch语句&#xff08;4&#xff09;分支结构 完 本章循环结构的…

Python 中的==操作符 和 is关键字

Python是一种功能强大的通用编程语言&#xff0c;提供了各种比较值和对象的方法。其中包括操作符和is关键字&#xff0c;它们的用途不同&#xff0c;但由于它们有时可以达到相同的目的&#xff0c;所以经常会被混淆。在本文中&#xff0c;我们将深入研究和is之间的区别&#xf…

解决:ModuleNotFoundError: No module named ‘bs4’

解决&#xff1a;ModuleNotFoundError: No module named ‘bs4’ 文章目录 解决&#xff1a;ModuleNotFoundError: No module named bs4背景报错问题报错翻译报错位置代码报错原因解决方法方法一&#xff0c;直接安装方法二&#xff0c;手动下载安装方法三&#xff0c;编译安装…

odoo17 | 视图字段验证约束

前言 前一章介绍了向模型添加一些业务逻辑的能力。现在我们可以将按钮链接到业务代码&#xff0c;但是我们如何防止用户输入错误的数据呢?例如&#xff0c;在我们的房地产模块中&#xff0c;没有什么可以阻止用户设置负预期价格。 Odoo提供了两种方法来设置自动验证的不变量…

Spring学习 Spring IOC

创建工程&#xff1a; 2.1.程序的耦合 耦合&#xff1a;耦合指的就是对象之间的依赖关系。对象之间的耦合越高&#xff0c;维护成本越高。 案例&#xff1a;没有引入IOC容器时系统的Web层、业务层、持久层存在耦合 /*** 持久层实现类*/ public class UserDaoImpl implements U…

如何实现无人机识别功能

无人机识别算法可以基于不同的传感器和技术&#xff0c;结合多种方法进行实现。以下是一些常见的无人机识别算法和技术&#xff1a; 视觉识别&#xff1a; 图像处理&#xff1a; 使用计算机视觉技术对无人机图像进行处理&#xff0c;包括特征提取、目标检测和跟踪等。深度学习&…

PHP语言B/S架构医院(安全)不良事件上报系统源码

医院安全&#xff08;不良&#xff09;事件上报系统采用无责的、自愿的填报不良事件方式&#xff0c;有效地减轻医护人员的思想压力&#xff0c;实现以事件为主要对象&#xff0c;可以自动、及时、实际地反应医院的安全、不良、近失事件的情况&#xff0c;更好地掌握不良事件的…

【python实战】python一行代码,实现文件共享服务器

一行代码实现文件共享 在一个局域网内&#xff0c;需要共享一个文件夹里内容。 我们可以在任意一台有python环境的电脑上&#xff0c;迅速架起一个http协议的服务&#xff0c;然后将文件夹里的文件内容共享出来。是的仅仅需要一行代码 就是这么简单 把电脑的相关项目文件通…

2023 hnust 湖南科技大学 大四上 商务智能 课程 期末考试 复习资料

前言 《听了课就能及格》由于老师发的复习PPT内容过多&#xff08;近两万字&#xff09;&#xff0c;因此在此大幅删减由于老师透露太少&#xff0c;删减全凭主观意志&#xff0c;请谨慎参考&#xff01;&#xff01;&#xff01;猜测逻辑 过于细碎概念的不考&#xff08;不算…

三、Kubernetes(K8s)入门(一)

视频教程连接k8s 入门到微服务项目实战.xmind链接&#xff1a;https://pan.baidu.com/s/1q04euH7baE8eXNyG3kPPbA 提取码&#xff1a;jej4比较好的笔记 kubectl命令的语法如下&#xff1a; kubectl [command] [type] [name] [flags]comand&#xff1a;指定要对资源执行的操作…

[足式机器人]Part2 Dr. CAN学习笔记-动态系统建模与分析 Ch02-6频率响应与滤波器

本文仅供学习使用 本文参考&#xff1a; B站&#xff1a;DR_CAN Dr. CAN学习笔记-动态系统建模与分析 Ch02-6频率响应与滤波器 1st order system 一阶系统 低通滤波器——Loss Pass Filter

使用.Net nanoFramework获取ESP32板载按键的点击事件

本文以 ESP32-S3-Zero 板载的按键为例&#xff0c;介绍了GPIO的使用方法&#xff0c;以及如何获取按键的点击事件。板载按钮作为自带的天然用户按钮&#xff0c;除了其本身的功能外&#xff0c;也可以作为某些应用场景下的简单的交互方式。 1. 引言 对于一般的产品来说&#x…