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

标签 c# .net .net-3.5 named-pipes

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

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

问题是,当线程等待传入数据时,您无法再向服务器发送消息,因为它卡在 WriteLine 调用上,因为我假设管道现在已绑定(bind)检查用于数据。

难道只是我没有正确处理这个问题吗?还是命名管道不应该像这样使用?我在命名管道上看到的示例似乎只有一种方式,客户端发送,服务器接收,尽管您可以将管道的方向指定为 InOut 或两者兼而有之。

如有任何帮助、指点或建议,我们将不胜感激!

到目前为止,这是代码:

// 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);
    }
}

最佳答案

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

关于c# - 你能用一个命名管道客户端读写吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8434837/

相关文章:

c# - C# 有无符号 double 吗?

c# - "empty line with semicolon"在 C# 中意味着什么?

c# - 通过 C# 构建基于 Windows 的客户端/服务器应用程序

.net - System.Net.WebClient 与代理身份验证 407 错误

c# - 是否有比 "fire and forget"更好、更可靠的模式来同时处理可变数量的异步任务?

c# - 检测 Windows 7 审核模式

c# - 如何保存动态复选框更改

c# - 我是否需要覆盖引用类型的 GetHashCode()?

具有多个聚合的 LINQ 查询

c# - .NET 的线程安全缓冲区