C# 您可以使用单个命名管道客户端进行读写吗?
我编写了一个小应用程序,它创建了一个命名管道服务器和一个连接到该服务器的客户端。您可以将数据发送到服务器,服务器将成功读取数据 我需要做的下一件事是接收来自服务器的消息,这样我就有了另一个线程,它会生成、驻留并等待传入的数据 问题是,当线程在等待传入数据时,您不能再向服务器发送消息,因为它挂在C# 您可以使用单个命名管道客户端进行读写吗?,c#,.net,.net-3.5,named-pipes,C#,.net,.net 3.5,Named Pipes,我编写了一个小应用程序,它创建了一个命名管道服务器和一个连接到该服务器的客户端。您可以将数据发送到服务器,服务器将成功读取数据 我需要做的下一件事是接收来自服务器的消息,这样我就有了另一个线程,它会生成、驻留并等待传入的数据 问题是,当线程在等待传入数据时,您不能再向服务器发送消息,因为它挂在WriteLine调用上,因为我假设管道现在已被数据绑定 那么,是不是我没有正确地处理这个问题?或者命名管道不打算这样使用吗?我在命名管道上看到的示例似乎只有一种方式,客户机发送,服务器接收,尽管您可以将管
WriteLine
调用上,因为我假设管道现在已被数据绑定
那么,是不是我没有正确地处理这个问题?或者命名管道不打算这样使用吗?我在命名管道上看到的示例似乎只有一种方式,客户机发送,服务器接收,尽管您可以将管道的方向指定为输入
,输出
或两者兼而有之
任何帮助、指点或建议都将不胜感激
以下是迄今为止的代码:
// 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);
}
}
不能从一个线程读取同一管道对象,也不能在另一个线程上写入同一管道对象。因此,虽然您可以创建一个协议,其中监听位置根据您发送的数据而变化,但不能同时执行这两项操作。要做到这一点,两侧都需要一个客户端和服务器管道 当然,只要不需要异步,这是可能的。这是真正的独立性,而您使用2个管道进行读写意味着真正的独立性,我想这样命名。听起来有点神秘。。所以我想你是说应该有一个用来阅读的烟斗和另一个用来写作的烟斗,因为你在任何时候都只能用一对一的动作?如果是的话,这是有道理的