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

sdnqo3pr  于 2023-05-19  发布在  .NET
关注(0)|答案(2)|浏览(187)

我已经写了一个小应用程序,它创建了一个命名管道服务器和一个连接到它的客户机。您可以将数据发送到服务器,并且服务器成功读取数据。
我需要做的下一件事是从服务器接收消息,所以我有另一个线程,它产生并等待传入的数据。
问题是,当线程等待传入数据时,您无法再向服务器发送消息,因为它挂起了WriteLine调用,因为我假设管道现在正在检查数据。
是不是因为我处理得不好?或者命名管道不应该这样使用?我看到的命名管道的例子似乎只有一个方向,客户端发送,服务器接收,尽管你可以指定管道的方向为InOut或两者兼而有之。
任何帮助,指针或建议将不胜感激!
下面是到目前为止的代码:

  1. // Variable declarations
  2. NamedPipeClientStream pipeClient;
  3. StreamWriter swClient;
  4. Thread messageReadThread;
  5. bool listeningStopRequested = false;
  6. // Client connect
  7. public void Connect(string pipeName, string serverName = ".")
  8. {
  9. if (pipeClient == null)
  10. {
  11. pipeClient = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut);
  12. pipeClient.Connect();
  13. swClient = new StreamWriter(pipeClient);
  14. swClient.AutoFlush = true;
  15. }
  16. StartServerThread();
  17. }
  18. // Client send message
  19. public void SendMessage(string msg)
  20. {
  21. if (swClient != null && pipeClient != null && pipeClient.IsConnected)
  22. {
  23. swClient.WriteLine(msg);
  24. BeginListening();
  25. }
  26. }
  27. // Client wait for incoming data
  28. public void StartServerThread()
  29. {
  30. listeningStopRequested = false;
  31. messageReadThread = new Thread(new ThreadStart(BeginListening));
  32. messageReadThread.IsBackground = true;
  33. messageReadThread.Start();
  34. }
  35. public void BeginListening()
  36. {
  37. string currentAction = "waiting for incoming messages";
  38. try
  39. {
  40. using (StreamReader sr = new StreamReader(pipeClient))
  41. {
  42. while (!listeningStopRequested && pipeClient.IsConnected)
  43. {
  44. string line;
  45. while ((line = sr.ReadLine()) != null)
  46. {
  47. RaiseNewMessageEvent(line);
  48. LogInfo("Message received: {0}", line);
  49. }
  50. }
  51. }
  52. LogInfo("Client disconnected");
  53. RaiseDisconnectedEvent("Manual disconnection");
  54. }
  55. // Catch the IOException that is raised if the pipe is
  56. // broken or disconnected.
  57. catch (IOException e)
  58. {
  59. string error = "Connection terminated unexpectedly: " + e.Message;
  60. LogError(currentAction, error);
  61. RaiseDisconnectedEvent(error);
  62. }
  63. }
w41d8nur

w41d8nur1#

不能从一个线程读取同一个管道对象,并在另一个线程上写入该对象。因此,虽然您可以创建一个协议,其中侦听位置根据您发送的数据而变化,但您不能同时做到这两点。要做到这一点,在两端都需要一个客户端和服务器管道。

wfveoks0

wfveoks02#

关键点是:

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

参数
PipeOptions.Asynchronous
指出了异步读写流的框架。

相关问题