优雅地关闭命名管道并处理流
Gracefully closing a named pipe and disposing of streams
我有一个双向命名管道。我不确定如何优雅地关闭它,但是,一旦我完成它 - 如果我从客户端关闭连接,服务器端在它试图处理 StreamReader 和 StreamWriter 时抛出异常我'我正在使用。我目前正在捕捉它,但对我来说这似乎是一项艰巨的工作。
服务器端代码:
Thread pipeServer = new Thread(ServerThread);
pipeServer.Start();
private void ServerThread(object data)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
log.Debug("Spawned thread " + threadId);
PipeSecurity ps = new PipeSecurity();
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
log.Debug("Pipe security settings set [Thread " + threadId + "]");
NamedPipeServerStream pipeServer =
new NamedPipeServerStream("RDPCommunicationPipe", PipeDirection.InOut, numThreads, PipeTransmissionMode.Message, PipeOptions.None, 0x1000, 0x1000, ps);
log.Debug("Pipe Servers created");
// Wait for a client to connect
log.Info("Pipe created on thread " + threadId + ". Listening for client connection.");
pipeServer.WaitForConnection();
log.Debug("Pipe server connection established [Thread " + threadId + "]");
Thread nextServer = new Thread(ServerThread);
nextServer.Start();
try
{
// Read the request from the client. Once the client has
// written to the pipe its security token will be available.
using (StreamReader sr = new StreamReader(pipeServer))
{
using (StreamWriter sw = new StreamWriter(pipeServer) { AutoFlush = true })
{
// Verify our identity to the connected client using a
// string that the client anticipates.
sw.WriteLine("I am the one true server!");
log.Debug("[Thread " + threadId + "]" + sr.ReadLine());
log.Info(string.Format("Client connected on thread {0}. Client ID: {1}", threadId, pipeServer.GetImpersonationUserName()));
while (!sr.EndOfStream)
{
log.Debug("[Thread " + threadId + "]" + sr.ReadLine());
}
}
}
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException e)
{
log.Error("ERROR: " + e);
}
}
客户端代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting...");
var client = new NamedPipeClientStream(".", "RDPCommunicationPipe", PipeDirection.InOut);
client.Connect();
Console.WriteLine("Pipe connected successfully");
using (StreamReader sr = new StreamReader(client))
{
using (StreamWriter sw = new StreamWriter(client) { AutoFlush = true })
{
string temp;
do
{
temp = sr.ReadLine();
Console.WriteLine(temp);
} while (temp.Trim() != "I am the one true server!");
sw.WriteLine("Message received and understood");
while (!string.IsNullOrEmpty(temp = Console.ReadLine()))
{
sw.WriteLine(temp);
}
}
}
client.Close();
}
}
直到我在客户端应用程序的空行上按回车键,它才完美运行,这终止了它,关闭了客户端。然后,服务器应用程序在到达 StreamWriter using
块的末尾时抛出 System.IO.IOException: Pipe is broken.
。如何正确处理我的流处理程序?
(代码基于发现的想法 here and here。)
I'm currently catching it, but that seems like a kludge job to me.
恕我直言,如果你想成为一个好邻居并处理你拥有的 StreamWriter
对象并仍然投入最少的努力,它就和你将要得到的一样好。
也就是说,在我看来,在这种特殊情况下,也可以注释掉对 Dispose()
的调用——或者在您的情况下,不使用 using
语句— 并包括另一条评论,解释在代码执行顺序中的那个点,您 知道 所有调用要做的就是抛出异常,因此没有意义成功了。
当然,如果您只是懒得处理 StreamWriter
,那么您会想要明确地处理您的管道流。您可能还想使用具有 leaveOpen
参数的 StreamWriter
构造函数,并为该参数传递 true
,作为一种记录您不使用 StreamWriter
的意图的方式拥有管道流对象。
无论哪种方式,您最终都会将对象留在终结器队列中,因为异常会绕过对 GC.SuppressFinalize()
的调用,(当然)也不会费心调用 Dispose()
根本。只要您不处理大量场景(即大量此类对象),就可以了。但这肯定不理想。
不幸的是,命名管道本身没有提供套接字所提供的那种"graceful closure"语义。也就是说,端点指示它们已完成写入的唯一方法是断开连接(对于服务器管道)或关闭(对于服务器或客户端管道)。这两个选项都不会使管道可供读取,因此在管道上实现优雅的关闭需要在应用程序协议本身内进行握手,而不是依赖于 I/O 对象。
除了这种不便(我承认,这与您的问题没有直接关系)之外,PipeStream.Flush()
的实现还检查管道是否可写。 尽管它无意写任何东西!最后一部分我觉得很烦人,当然也直接导致了你问的问题。在我看来,.NET Framework 中的代码在那些异常带来的麻烦多于好处的情况下特意抛出异常似乎是不合理的。
综上所述,您还有一些其他选择:
- Subclass
NamedPipeServerStream
和 NamedPipeClientStream
类型,并覆盖 Flush()
方法,使其真正不做任何事情。或者说,如果你能做到这一点就好了。但是那些类型是sealed
,所以你不能。
- 替代子class 那些类型,您可以将它们包装在您自己的
Stream
实现中。这更麻烦,特别是因为您可能想要覆盖所有异步成员,至少如果您打算在 I/O 性能感兴趣的任何情况下使用这些对象。
- 使用单独的单向管道进行读取和写入。在此实现中,您可以关闭
StreamWriter
本身作为关闭连接的一种方式,这会导致正确的顺序(即刷新发生在管道关闭之前)。这也解决了优雅的关闭问题,因为每个连接有两个管道,您可以拥有与套接字相同的基本 "half-closed" 语义。当然,由于要确定哪对管道连接是相互配合的,因此这个选项变得非常复杂。
这两个(也就是第二个和第三个,也就是实际可行的那个)都有一些明显的缺点。必须拥有自己的 Stream
class 是一件痛苦的事情,因为需要所有重复的代码。并且将管道对象计数加倍似乎是解决异常的一种激进方法(但它可能是支持优雅闭包语义的可接受且理想的实现,具有消除抛出异常问题的快乐副作用 StreamWriter.Dispose()
).
请注意,在高容量场景中(但是,为什么要使用管道?),高频率抛出和捕获异常可能是个问题(它们很昂贵)。因此,在这种情况下,这两个替代选项中的一个或另一个可能更可取,而不是捕获异常并且只是不打扰 close/dispose 你的 StreamWriter
(两者都会增加会干扰的低效率高容量场景)。
我有一个双向命名管道。我不确定如何优雅地关闭它,但是,一旦我完成它 - 如果我从客户端关闭连接,服务器端在它试图处理 StreamReader 和 StreamWriter 时抛出异常我'我正在使用。我目前正在捕捉它,但对我来说这似乎是一项艰巨的工作。
服务器端代码:
Thread pipeServer = new Thread(ServerThread);
pipeServer.Start();
private void ServerThread(object data)
{
int threadId = Thread.CurrentThread.ManagedThreadId;
log.Debug("Spawned thread " + threadId);
PipeSecurity ps = new PipeSecurity();
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
log.Debug("Pipe security settings set [Thread " + threadId + "]");
NamedPipeServerStream pipeServer =
new NamedPipeServerStream("RDPCommunicationPipe", PipeDirection.InOut, numThreads, PipeTransmissionMode.Message, PipeOptions.None, 0x1000, 0x1000, ps);
log.Debug("Pipe Servers created");
// Wait for a client to connect
log.Info("Pipe created on thread " + threadId + ". Listening for client connection.");
pipeServer.WaitForConnection();
log.Debug("Pipe server connection established [Thread " + threadId + "]");
Thread nextServer = new Thread(ServerThread);
nextServer.Start();
try
{
// Read the request from the client. Once the client has
// written to the pipe its security token will be available.
using (StreamReader sr = new StreamReader(pipeServer))
{
using (StreamWriter sw = new StreamWriter(pipeServer) { AutoFlush = true })
{
// Verify our identity to the connected client using a
// string that the client anticipates.
sw.WriteLine("I am the one true server!");
log.Debug("[Thread " + threadId + "]" + sr.ReadLine());
log.Info(string.Format("Client connected on thread {0}. Client ID: {1}", threadId, pipeServer.GetImpersonationUserName()));
while (!sr.EndOfStream)
{
log.Debug("[Thread " + threadId + "]" + sr.ReadLine());
}
}
}
}
// Catch the IOException that is raised if the pipe is broken
// or disconnected.
catch (IOException e)
{
log.Error("ERROR: " + e);
}
}
客户端代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting...");
var client = new NamedPipeClientStream(".", "RDPCommunicationPipe", PipeDirection.InOut);
client.Connect();
Console.WriteLine("Pipe connected successfully");
using (StreamReader sr = new StreamReader(client))
{
using (StreamWriter sw = new StreamWriter(client) { AutoFlush = true })
{
string temp;
do
{
temp = sr.ReadLine();
Console.WriteLine(temp);
} while (temp.Trim() != "I am the one true server!");
sw.WriteLine("Message received and understood");
while (!string.IsNullOrEmpty(temp = Console.ReadLine()))
{
sw.WriteLine(temp);
}
}
}
client.Close();
}
}
直到我在客户端应用程序的空行上按回车键,它才完美运行,这终止了它,关闭了客户端。然后,服务器应用程序在到达 StreamWriter using
块的末尾时抛出 System.IO.IOException: Pipe is broken.
。如何正确处理我的流处理程序?
(代码基于发现的想法 here and here。)
I'm currently catching it, but that seems like a kludge job to me.
恕我直言,如果你想成为一个好邻居并处理你拥有的 StreamWriter
对象并仍然投入最少的努力,它就和你将要得到的一样好。
也就是说,在我看来,在这种特殊情况下,也可以注释掉对 Dispose()
的调用——或者在您的情况下,不使用 using
语句— 并包括另一条评论,解释在代码执行顺序中的那个点,您 知道 所有调用要做的就是抛出异常,因此没有意义成功了。
当然,如果您只是懒得处理 StreamWriter
,那么您会想要明确地处理您的管道流。您可能还想使用具有 leaveOpen
参数的 StreamWriter
构造函数,并为该参数传递 true
,作为一种记录您不使用 StreamWriter
的意图的方式拥有管道流对象。
无论哪种方式,您最终都会将对象留在终结器队列中,因为异常会绕过对 GC.SuppressFinalize()
的调用,(当然)也不会费心调用 Dispose()
根本。只要您不处理大量场景(即大量此类对象),就可以了。但这肯定不理想。
不幸的是,命名管道本身没有提供套接字所提供的那种"graceful closure"语义。也就是说,端点指示它们已完成写入的唯一方法是断开连接(对于服务器管道)或关闭(对于服务器或客户端管道)。这两个选项都不会使管道可供读取,因此在管道上实现优雅的关闭需要在应用程序协议本身内进行握手,而不是依赖于 I/O 对象。
除了这种不便(我承认,这与您的问题没有直接关系)之外,PipeStream.Flush()
的实现还检查管道是否可写。 尽管它无意写任何东西!最后一部分我觉得很烦人,当然也直接导致了你问的问题。在我看来,.NET Framework 中的代码在那些异常带来的麻烦多于好处的情况下特意抛出异常似乎是不合理的。
综上所述,您还有一些其他选择:
- Subclass
NamedPipeServerStream
和NamedPipeClientStream
类型,并覆盖Flush()
方法,使其真正不做任何事情。或者说,如果你能做到这一点就好了。但是那些类型是sealed
,所以你不能。 - 替代子class 那些类型,您可以将它们包装在您自己的
Stream
实现中。这更麻烦,特别是因为您可能想要覆盖所有异步成员,至少如果您打算在 I/O 性能感兴趣的任何情况下使用这些对象。 - 使用单独的单向管道进行读取和写入。在此实现中,您可以关闭
StreamWriter
本身作为关闭连接的一种方式,这会导致正确的顺序(即刷新发生在管道关闭之前)。这也解决了优雅的关闭问题,因为每个连接有两个管道,您可以拥有与套接字相同的基本 "half-closed" 语义。当然,由于要确定哪对管道连接是相互配合的,因此这个选项变得非常复杂。
这两个(也就是第二个和第三个,也就是实际可行的那个)都有一些明显的缺点。必须拥有自己的 Stream
class 是一件痛苦的事情,因为需要所有重复的代码。并且将管道对象计数加倍似乎是解决异常的一种激进方法(但它可能是支持优雅闭包语义的可接受且理想的实现,具有消除抛出异常问题的快乐副作用 StreamWriter.Dispose()
).
请注意,在高容量场景中(但是,为什么要使用管道?),高频率抛出和捕获异常可能是个问题(它们很昂贵)。因此,在这种情况下,这两个替代选项中的一个或另一个可能更可取,而不是捕获异常并且只是不打扰 close/dispose 你的 StreamWriter
(两者都会增加会干扰的低效率高容量场景)。