首页 技术 正文
技术 2022年11月15日
0 收藏 976 点赞 2,997 浏览 6215 个字
//管道服务类
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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,082
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,556
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,406
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,179
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,815
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,898