C# 管道通信 (client —— server)Framework2.0版本也可用
//管道服务类
public class PipServer
{
[DllImport("kernel32.dll", SetLastError = true)] public static extern SafeFileHandle CreateNamedPipe( String pipeName, //管道名 uint dwOpenMode,//管道类型 uint dwPipeMode,//管道参数 uint nMaxInstances,//管道能创建的最大实例数量 uint nOutBufferSize, //输出缓冲区长度 0表示默认 uint nInBufferSize,//输入缓冲区长度 0表示默认 uint nDefaultTimeOut,//超时时间 IntPtr lpSecurityAttributes);//指定一个SECURITY_ATTRIBUTES结构,或者传递零值 [DllImport("kernel32.dll", SetLastError = true)] public static extern int ConnectNamedPipe( SafeFileHandle hNamedPipe, IntPtr lpOverlapped); public const uint DUPLEX = (0x00000003); public const uint FILE_FLAG_OVERLAPPED = (0x40000000); public class Client
{
public SafeFileHandle handle; public FileStream stream;
} public delegate void RecivedMessageDelegate(string message); public delegate void MessageReceivedHandler(Client client, string message); public event MessageReceivedHandler MessageReceived; public const int BUFFER_SIZE = ; string pipeName; Thread listenThread; bool running; List<Client> clients; public string PipeName
{
get { return this.pipeName; } set { this.pipeName = value; }
} public bool Running
{
get { return this.running; }
} public PipServer()
{
this.clients = new List<Client>();
} public void Start()
{
this.listenThread = new Thread(new ThreadStart(ListenForClients)); this.listenThread.Start(); this.running = true;
} private void ListenForClients()
{
while (true)
{
SafeFileHandle clientHandle = CreateNamedPipe(
this.pipeName, DUPLEX | FILE_FLAG_OVERLAPPED, , , BUFFER_SIZE, BUFFER_SIZE, , IntPtr.Zero); if (clientHandle.IsInvalid) return; int success = ConnectNamedPipe(clientHandle, IntPtr.Zero); if (success == ) return; Client client = new Client(); client.handle = clientHandle; lock (clients) this.clients.Add(client); Thread readThread = new Thread(new ParameterizedThreadStart(Read)); readThread.Start(client);
}
} private void Read(object clientObj)
{
Client client = (Client)clientObj; client.stream = new FileStream(client.handle, FileAccess.ReadWrite, BUFFER_SIZE, true); byte[] buffer = new byte[BUFFER_SIZE]; //ASCIIEncoding encoder = new ASCIIEncoding(); UTF8Encoding encoder = new UTF8Encoding();//可以传汉字 while (true)
{
int bytesRead = ; try
{
bytesRead = client.stream.Read(buffer, , BUFFER_SIZE);
}
catch
{
break;
} if (bytesRead == ) break; if (this.MessageReceived != null) this.MessageReceived(client, encoder.GetString(buffer, , bytesRead));
}
client.stream.Close(); client.handle.Close(); lock (this.clients) this.clients.Remove(client);
} public void SendMessage(string message)
{
lock (this.clients)
{
ASCIIEncoding encoder = new ASCIIEncoding(); byte[] messageBuffer = encoder.GetBytes(message); foreach (Client client in this.clients)
{
client.stream.Write(messageBuffer, , messageBuffer.Length); client.stream.Flush();
}
}
}
}
//启动管道服务
public partial class Form_PipServer : Form
{
public Form_PipServer()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
ServerPort serverPort;
try
{
serverPort = new ServerPort(this, new PipServer.RecivedMessageDelegate(DisplayMessage)); serverPort.pipeServer = new PipServer(); serverPort.PipServerStart(); }
catch
{ } } void DisplayMessage(string message)
{
textBox1.Text += message + "\r\n";
} public class ServerPort
{ private Delegate sendMessage = null; private ContainerControl mainForm; public PipServer pipeServer = null; public ServerPort(ContainerControl form, Delegate sendmessage)
{
mainForm = form; sendMessage = sendmessage;
} void SendMsg(string msg)
{
this.mainForm.Invoke(sendMessage, new Object[] { msg });
} void PipeServer_MessageReceived(PipServer.Client client, string message)
{
if (!message.Equals(""))
{
SendMsg("接收到的信息是:" + message);
}
else
{
SendMsg("消息未收到???");
}
} public void MessageSend()
{ } public void PipServerStart()
{
try
{
if (!this.pipeServer.Running)
{
this.pipeServer.PipeName = "\\\\.\\Pipe\\piperulecfg";//管道名称 this.pipeServer.Start(); this.pipeServer.MessageReceived += new PipServer.MessageReceivedHandler(PipeServer_MessageReceived);
}
}
catch
{
}
}
}
}
//客户端类 public class PipClient
{
[DllImport("kernel32.dll", SetLastError = true)] public static extern SafeFileHandle CreateFile( String pipeName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplate); public const uint GENERIC_READ = (0x80000000); public const uint GENERIC_WRITE = (0x40000000); public const uint OPEN_EXISTING = ; public const uint FILE_FLAG_OVERLAPPED = (0x40000000); public delegate void MessageReceivedHandler(string message); public event MessageReceivedHandler MessageReceived; public const int BUFFER_SIZE = ; string pipeName; private FileStream stream; private SafeFileHandle handle; Thread readThread; bool connected; public bool Connected
{
get { return this.connected; }
} public string PipeName
{
get { return this.pipeName; } set { this.pipeName = value; }
} public void Connect()
{
this.handle = CreateFile( //管道属于一种特殊的文件 this.pipeName, //创建的文件名 GENERIC_READ | GENERIC_WRITE, //文件模式 , //是否共享 IntPtr.Zero, //指向一个SECURITY_ATTRIBUTES结构的指针 OPEN_EXISTING,//创建参数 FILE_FLAG_OVERLAPPED,//文件属性(隐藏,只读)NORMAL为默认属性 IntPtr.Zero);//模板创建文件的句柄 if (this.handle.IsInvalid)
return; this.connected = true; this.stream = new FileStream(this.handle, FileAccess.ReadWrite, BUFFER_SIZE, true); this.readThread = new Thread(new ThreadStart(Read)); this.readThread.Start();
} public void Read()
{
byte[] readBuffer = new byte[BUFFER_SIZE]; ASCIIEncoding encoder = new ASCIIEncoding(); while (true)
{
int bytesRead = ; try
{
bytesRead = this.stream.Read(readBuffer, , BUFFER_SIZE);
}
catch
{
break;
} if (bytesRead == )
break; if (this.MessageReceived != null) this.MessageReceived(encoder.GetString(readBuffer, , bytesRead));
}
this.stream.Close(); this.handle.Close();
} public void SendMessage(string message)
{
//ASCIIEncoding encoder = new ASCIIEncoding(); UTF8Encoding encoder = new UTF8Encoding();//可以传汉字 byte[] messageBuffer = encoder.GetBytes(message); this.stream.Write(messageBuffer, , messageBuffer.Length); this.stream.Flush();
}
}
//客户端发送消息到服务端
public partial class Form_PipClient : Form
{
public Form_PipClient()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
string szInfo = textBox1.Text;
ClientPort.MessagePipeStart(szInfo);
} public class ClientPort
{
private static PipClient pipeClient; public static void MessagePipeStart(string szInfo)
{
if (pipeClient == null)
{
pipeClient = new PipClient(); pipeClient.MessageReceived += new PipClient.MessageReceivedHandler(pipeClient_MessageReceived);
} if (!pipeClient.Connected)
{
pipeClient.PipeName = "\\\\.\\Pipe\\piperulecfg"; pipeClient.Connect();
} if (pipeClient != null && pipeClient.Connected)
{
MessageSend(szInfo);
}
else
{
MessageBox.Show("连接建立失败,请确保服务端程序已经被打开。");
}
} static void MessageSend(string str)
{
pipeClient.SendMessage(str);
}
//客户端接收消息
static void pipeClient_MessageReceived(string message)
{ }
}
}
欢迎加群交流 QQ群 830426796
C# 管道通信 (client —— server)Framework2.0版本也可用的更多相关文章
- 运维监控-基于yum的方式部署Zabbix Server 4.0 版本
运维监控-基于yum的方式部署Zabbix Server 4.0 版本 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.如何选择zabbix版本 1>.打开zabbix官方 ...
- nginx1.14.0版本高可用——keepalived双机热备
nginx不支持主从,所以我们需要使用keepalive支持高可用. keepalived重要知识点 在局域网内,每个主机上各安装一个keepalived,注意关闭防火墙firewalld,然后设定一 ...
- IIS6中给Framework2,。0站点的虚拟目录(2.0版本)下发布Web API项目(4.0版本)问题处理
Web-API项目以虚拟目录形式部署到IIS6/IIS7 若原有站点为Framework2.0版本,在此站点(或虚拟目录站点)下,新增API虚拟目录,然后选择Framework4.0版本,IIS6和I ...
- MySQL Server8.0版本时出现Client does not support authentication protocol requested by server
MySQL Server8.0版本时出现Client does not support authentication protocol requested by server 解决方法: 1.roo ...
- Hadoop源码解析之 rpc通信 client到server通信
rpc是Hadoop分布式底层通信的基础,无论是client和namenode,namenode和datanode,以及yarn新框架之间的通信模式等等都是采用的rpc方式. 下面我们来概要分析一下H ...
- 分析一个socket通信: server/client
分析一个socket通信: server/client1 server 1. 创建一个server_socket文件,并绑定端口,然后监听端口 (socket, bind, listen) 2. 查询 ...
- MySQL 8.0版本连接报错:Could not create connection to database server.
准备搭建一个Spring Boot 组合mybatis的项目,数据库采用的是MySQL 8.0.11按照以往的配置,使用插件mybatis-generator-maven-plugin生成代码时,一直 ...
- 基于yum的方式安装Cloudera Manager Server(使用Mysql 8.0版本)
基于yum的方式安装Cloudera Manager Server(使用Mysql 8.0版本) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.安装和配置元数据库 1>. ...
- (C#2,.net framework2.0,Visual Studio 2003)之前版本
(C#2,.net framework2.0,Visual Studio 2003)之前版本归为最初的版本(主要是针对.net framework),其主要定义了最基本的类型.特性. 1.基本的类型 ...
随机推荐
- 五分钟学会conda常用命令
文章目录 conda常用命令 1. 获取版本号 2. 获取帮助 3. 环境管理 4. 分享环境 5. 包管理 conda常用命令 1. 获取版本号 conda --version 或 conda -V ...
- Activiti架构分析及源码详解
目录 Activiti架构分析及源码详解 引言 一.Activiti设计解析-架构&领域模型 1.1 架构 1.2 领域模型 二.Activiti设计解析-PVM执行树 2.1 核心理念 2. ...
- 起言-----UE4学习方法
1.bilibili 2.官网教程 3.我觉得以上两个就够了 官方文档链接 https://docs.unrealengine.com/ 官网在线视频链接 https://learn.unrealen ...
- ssh服务介绍及配置
一.ssh介绍 1.什么是 ssh ssh 是 Secure Shell 的缩写,是一个建立在应用层上的安全远程管理协议.ssh 是目前较为可靠的传输协议,专为远程登录会话和其他网络服务提供安全性.利 ...
- HttpRunner学习6--使用parameters参数化
前言 在使用HttpRunner测试过程中,我们可能会遇到这种场景: 账号登录功能,需要输入用户名和密码,设计测试用例后有 N 种组合情况 如果测试组合比较少,比如只有2个,那我们直接在YAML脚本中 ...
- NLP标注工具brat 配置文件说明
快速搭建brat 通过docker: docker run --name=brat -d -p 38080:80 -e BRAT_USERNAME=brat -e BRAT_PASSWORD=brat ...
- 全字段多条件搜索(api接口)
近期在做项目时遇到了一个全表全字段多条件搜索的需求,在平时搜索最常见的就是 字段+like +‘% 条件%’这种模式,但遇到多条件多字段时,这种就不适用了. 表字段已知,条件未知,条件数量未知,这种情 ...
- C# 多线程总结 异常处理 线程取消 锁(lock)
那么什么时候能用多线程? 任务能并发的时候 多线程能干嘛?提升速度/优化用户体验 网站首页:A数据库 B接口 C分布式服务 D搜索引擎,适合多线程并发,都完成后才能返回给用户,需要等待WaitAll列 ...
- 2019 Vue开发指南:你都需要学点啥?
转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者.原文出处:https://dzone.com/articles/vue-development-in-2019 ...
- 分布式图数据库 Nebula Graph 中的集群快照实践
1 概述 1.1 需求背景 图数据库 Nebula Graph 在生产环境中将拥有庞大的数据量和高频率的业务处理,在实际的运行中将不可避免的发生人为的.硬件或业务处理错误的问题,某些严重错误将导致集群 ...