出错前服务端核心代码:
private static NamedPipeServerStream _pipeServer = new NamedPipeServerStream("Pipe", PipeDirection.InOut, 1); private void WorkerThread() { try { _pipeServer.WaitForConnection(); var ss = new StreamString(_pipeServer); ss.WriteString("I am the one true server!"); var cmdText = ss.ReadString(); if (cmdText == "Are you Free?") { var result = _engine.IsHome(_engine.State); ss.WriteString(result.ToString()); } } catch (ThreadAbortException) { return; } catch (Exception ex) { return; } }
客户端核心代码:
using (var pipeClient = new NamedPipeClientStream(".", "Pipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { pipeClient.Connect(500); if (pipeClient.IsConnected) { var ss = new StreamString(pipeClient); if (ss.ReadString() == "I am the one true server!") { ss.WriteString("Are you Free?"); bool.TryParse(ss.ReadString(), out _isFree); } }
}
通信逻辑:客户端一直去判断服务端是否空闲。
可以看出来:客户端一直是起一个新的实例去通信服务端。服务端确实一个静态的唯一的实例
出现问题。客户端只能去通信一次,再一次通信报错,出现信号灯超时问题。
原因:服务端实例返回客户端信息后,通道关闭掉了。不再会等待连接。
解决办法:1.服务端每次循环启动新的管道去监听。
2.唯一实例的话。循环关闭连接再重新打开去监听。如下.
public void Stop() { _running = false; _pipeServer.Disconnect(); } private void WorkerThread() { try { _pipeServer.WaitForConnection(); var ss = new StreamString(_pipeServer); ss.WriteString("I am the one true server!"); var cmdText = ss.ReadString(); if (cmdText == "Are you Free?") { var result = _engine.IsHome(_engine.State); ss.WriteString(result.ToString()); } Stop(); WorkerThread(); } catch (ThreadAbortException) { return; } catch (Exception ex) { return; } }