作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在制作一个多客户端命名管道服务器。客户端正确连接到服务器,但每当我尝试通过服务器或客户端写入管道时,代码都会卡在 write 方法上。关于写入方法卡住的任何原因?
服务器代码:
public void ListenForConnections()
{
Thread startListening = new Thread(AcceptConnections);
startListening.Start(PipeName);
}
public static void AcceptConnections(object ServerPipeName)
{
while (true)
{
try
{
NamedPipeServerStream pipeServer =
new NamedPipeServerStream(ServerPipeName.ToString(),
PipeDirection.InOut,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Message);
pipeServer.WaitForConnection();
pipeServer.ReadMode = PipeTransmissionMode.Message;
//A client has connected
Pipes.Add(pipeServer);
index++;
Thread Poll = new Thread(PollPipe);
Poll.Start(pipeServer);
}
catch (Exception ex)
{
return;
}
}
}
public static void PollPipe(Object Pipe)
{
byte[] bytes = new byte[1024];
NamedPipeServerStream PipeStream = (NamedPipeServerStream)Pipe;
MemoryStream ms = new MemoryStream();
do
{
ms.Write(bytes, 0, PipeStream.Read(bytes, 0, bytes.Length));
} while (!PipeStream.IsMessageComplete);
}
public void BroadcastObject(GlassSquidObject obj)
{
long length = 0;
byte[] bytes;
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ws = new MemoryStream())
{
formatter.Serialize(ws, obj);
length = ws.Length;
bytes = ws.GetBuffer();
}
for (int i = 0; i < Pipes.Count; i++)
{
Pipes[i].Write(bytes, 0, bytes.Length);
}
}
}
这是我的客户的代码:
public bool ConnectToPipe()
{
if (String.IsNullOrWhiteSpace(PipeName))
return false;
PipeClient = new NamedPipeClientStream(Address, PipeName, PipeDirection.InOut);
try
{
PipeClient.Connect(5000);
Thread readThread = new Thread(PollPipe);
readThread.Start(PipeClient);
}
catch (Exception ex)
{
return false;
}
return true;
}
public bool WriteObject(GlassSquidObject obj)
{
long length = 0;
byte[] bytes;
try
{
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ws = new MemoryStream())
{
formatter.Serialize(ws, obj);
length = ws.Length;
bytes = ws.GetBuffer();
}
PipeClient.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
return false;
}
return true;
}
public static void PollPipe(Object Pipe)
{
byte[] bytes = new byte[1024];
NamedPipeClientStream PipeStream = (NamedPipeClientStream)Pipe;
PipeStream.ReadMode = PipeTransmissionMode.Message;
MemoryStream ms = new MemoryStream();
do
{
ms.Write(bytes, 0, PipeStream.Read(bytes, 0, bytes.Length));
} while (!PipeStream.IsMessageComplete);
}
最佳答案
我仍然不确定写入等待的是什么,但我找到了解决我的问题的方法/变通方法。通过将 NamedPipe 构造函数中的 PipeOptions 设置为异步,读取/写入成功完成!
关于c# - 命名管道在写入时挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735913/
我是一名优秀的程序员,十分优秀!