Iai*_*ard 5 .net c# named-pipes .net-3.5
我写了一个小应用程序,创建一个命名管道服务器和一个连接它的客户端.您可以将数据发送到服务器,服务器可以成功读取数据.
我需要做的下一件事是从服务器接收消息,所以我有另一个产生并坐下来等待传入数据的线程.
问题是,当线程处于等待传入数据的状态时,您不能再将消息发送到服务器,因为它会挂起,WriteLine因为我认为管道现在已经被绑定检查数据.
那只是我没有正确接近这个吗?或者命名管道不应该像这样使用?我在命名管道上看到的示例似乎只是单向,客户端发送和服务器接收,尽管您可以指定管道的方向In,Out或两者.
任何帮助,指针或建议将不胜感激!
到目前为止,这是代码:
// Variable declarations
NamedPipeClientStream pipeClient;
StreamWriter swClient;
Thread messageReadThread;
bool listeningStopRequested = false;
// Client connect
public void Connect(string pipeName, string serverName = ".")
{
if (pipeClient == null)
{
pipeClient = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut);
pipeClient.Connect();
swClient = new StreamWriter(pipeClient);
swClient.AutoFlush = true;
}
StartServerThread();
}
// Client send message
public void SendMessage(string msg)
{
if (swClient != null && pipeClient != null && pipeClient.IsConnected)
{
swClient.WriteLine(msg);
BeginListening();
}
}
// Client wait for incoming data
public void StartServerThread()
{
listeningStopRequested = false;
messageReadThread = new Thread(new ThreadStart(BeginListening));
messageReadThread.IsBackground = true;
messageReadThread.Start();
}
public void BeginListening()
{
string currentAction = "waiting for incoming messages";
try
{
using (StreamReader sr = new StreamReader(pipeClient))
{
while (!listeningStopRequested && pipeClient.IsConnected)
{
string line;
while ((line = sr.ReadLine()) != null)
{
RaiseNewMessageEvent(line);
LogInfo("Message received: {0}", line);
}
}
}
LogInfo("Client disconnected");
RaiseDisconnectedEvent("Manual disconnection");
}
// Catch the IOException that is raised if the pipe is
// broken or disconnected.
catch (IOException e)
{
string error = "Connection terminated unexpectedly: " + e.Message;
LogError(currentAction, error);
RaiseDisconnectedEvent(error);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 4
您无法从一个线程读取同一管道对象并在另一线程上写入。因此,虽然您可以创建一个协议,其中收听位置根据您发送的数据而变化,但您不能同时执行这两项操作。您需要在两侧都有一个客户端和服务器管道来执行此操作。