你能用一个命名管道客户端读写吗?

问题描述 投票:0回答:2

我写了一个小应用程序来创建一个命名管道服务器和一个连接到它的客户端。可以向服务器发送数据,服务器读取成功

我需要做的下一件事是从服务器接收消息,所以我有另一个线程产生并等待传入数据。

问题是,当线程等待传入数据时,您无法再向服务器发送消息,因为它挂在

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);
    }
}
c# .net .net-3.5 named-pipes
2个回答
4
投票

您不能从一个线程读取并在另一个线程上写入同一个管道对象。因此,虽然您可以创建一个协议,其中收听位置会根据您发送的数据而变化,但您不能同时执行这两项操作。您将需要在两侧都有一个客户端和服务器管道来执行此操作。


0
投票

当我想同时读取和写入流到管道时,我也面临同样的问题。 最后我解决了,关键是:

clientStream = new NamedPipeClientStream(".", clientPipeName, PipeDirection.InOut, PipeOptions.Asynchronous);

参数

PipeOptions.Asynchronous

指出异步读/写流的框架。

© www.soinside.com 2019 - 2024. All rights reserved.