我正在创建一个Windows服务,该服务将与另一个应用程序进行通信。我面临的问题是NamedPipeServerStream
会在客户端断开连接后立即关闭。我希望服务器应该保持打开状态,以便每当客户端应用程序启动时,它就会连接起来。
我不想使用WCF,消息会很小,所以我只想使用命名管道使其简单。多个客户端可以连接到该服务。有没有办法让服务器始终运行?
这是我到目前为止所拥有的:
var server = new NamedPipeServerStream("pipeeee123");
server.SetAccessControl(pipeSa);
server.WaitForConnection();
StreamReader reader = new StreamReader(server);
StreamWriter writer = new StreamWriter(server);
while (true)
{
var line = reader.ReadLine();
this.EventLog.WriteEntry("Got command " + line, EventLogEntryType.Information);
var resp = HandleCommand(line);
writer.WriteLine(resp);
writer.Flush();
}
答案 0 :(得分:0)
命名管道实例应在客户端断开连接时终止,请参阅:https://docs.microsoft.com/en-us/windows/win32/ipc/named-pipe-instances?redirectedfrom=MSDN。
有关多个客户服务,请参见以下项目:https://www.codeproject.com/Articles/864679/Creating-a-Server-Using-Named-Pipes
也许也有帮助: How to use named pipes in C# correctly -- several connections, server recreation etc
答案 1 :(得分:0)
看一下这段代码。
var server = new NamedPipeServerStream("PipesOfPiece");
StreamReader reader = new StreamReader(server);
StreamWriter writer = new StreamWriter(server);
while (true)
{
if (!server.IsConnected)
{
try
{
server.WaitForConnection();
}
catch (IOException)
{
server.Disconnect();
continue;
}
}
var line = reader.ReadLine();
if (!server.IsConnected)
{
continue;
}
if(!string.IsNullOrEmpty(line))
{
writer.WriteLine(String.Join("", line.Reverse()));
}
writer.Flush();
}
从我看到的结果来看,您的服务器刚刚崩溃是因为您没有正确处理连接+边缘情况的重新打开。 另外,考虑一下您一次只能使用一个客户端实例的事实。
答案 2 :(得分:0)
我知道它不是异步的,但是如果有人想要一个同步版本,我可以使用以下命令使其工作:
NamedPipeServerStream server = new NamedPipeServerStream("pipeee",
PipeDirection.InOut, 10,
PipeTransmissionMode.Message,
PipeOptions.WriteThrough, 1024, 1024, pipeSecurity);
while (true)
{
// re-connect if disconnected
if (!server.IsConnected)
{
server = new NamedPipeServerStream("pipeee",
PipeDirection.InOut, 10,
PipeTransmissionMode.Message,
PipeOptions.WriteThrough, 1024, 1024, pipeSecurity);
}
server.WaitForConnection();
StreamReader reader = new StreamReader(server);
StreamWriter writer = new StreamWriter(server);
while (true)
{
var line = reader.ReadLine();
var resp = HandleCommand(line);
writer.WriteLine(resp);
writer.Flush();
// exit inner loop if disconnected, outer loop will handle re connection
if(!server.IsConnected)
{
break;
}
}
}