我想出了以下代码:
class IPCServer
{
private Thread ipcServerThread;
private NamedPipeServerStream pipeServer;
public IPCServer()
{
pipeServer = new NamedPipeServerStream("iMedCallInfoPipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
}
public void SendMessage (String message) {
ThreadStart ipcServerThreadInfo = () => WriteToPipe(message);
ipcServerThread = new Thread(ipcServerThreadInfo);
ipcServerThread.Start();
}
private void WriteToPipe(String message)
{
if (pipeServer.IsConnected)
{
byte[] bytes = Encoding.UTF8.GetBytes(message);
pipeServer.Write(bytes, 0, bytes.Length);
pipeServer.WaitForPipeDrain();
pipeServer.Flush();
}
}
}
class ICPClient
{
public void Read(int TimeOut = 1000)
{
try
{
NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "iMedCallInfoPipe", PipeDirection.In, PipeOptions.None);
pipeStream.Connect(TimeOut);
using (StreamReader sr = new StreamReader(pipeStream))
{
string _buffer;
while ((_buffer = sr.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", _buffer);
}
}
}
catch (TimeoutException)
{
}
}
}
这是管道通信解决方案的客户端服务器。但是我需要服务器异步写入消息,客户端在它们弹出时读取它们,也是异步的。我怎样才能做到这一点?有很多示例,但其中大多数都考虑客户端写入服务器,我不确定如何实现我的目标,尤其是使用我已经编写的代码......