[英]Named Pipe hangs on write
我正在制作一個名為 Pipe 服務器的多客戶端。 客戶端正確連接到服務器,但每當我嘗試通過服務器或客戶端寫入 pipe 時,代碼會掛在 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設置為Asynchronous,讀取/寫入成功完成!
在以下情況下,我也遇到了這個問題:
我通過在每次write
調用之前讀取 pipe 來解決它,它為我解決了這個問題。
我不完全確定,但我認為這可能是為了防止數據丟失,pipe 表現得像“忙”,等待讀取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.