我有一个双向命名管道。我不确定如何优雅地关闭它,但是,一旦完成,我会关闭-如果我从客户端关闭连接,则服务器端在尝试处置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);
}
}
Run Code Online (Sandbox Code Playgroud)
客户端代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
直到我在客户端应用程序中的空白行上按Enter键,它会终止,并关闭客户端,它才能正常运行。然后,服务器应用程序System.IO.IOException: Pipe is broken.到达StreamWriter using块的末尾时将引发一个。如何正确处理流处理程序?
我目前正在抓住它,但是对我来说这似乎是一项艰巨的工作。
恕我直言,如果您想成为一个好邻居并处置您拥有的StreamWriter物品并仍然付出最小的努力,那将和您将要获得的一样好。
就是说,在我看来,在这种特殊情况下,也可以将对的调用注释掉Dispose()(或者在您的情况下,不使用该using语句),并在执行顺序中包含另一条注释来解释这一点,这也很好。在您的代码中,您知道该调用将要执行的所有操作均引发异常,因此进行该操作毫无意义。
当然,如果您只是不想处理StreamWriter,那么您将希望显式处理管道流。您可能还希望使用StreamWriter具有leaveOpen参数的构造函数,并传递true该参数,以证明您没有StreamWriter自己的管道流对象的意图。
无论哪种方式,您都将最终对象留在终结器队列中,因为该异常绕过了对的调用GC.SuppressFinalize(),(当然)根本不会打扰Dispose()。只要您不处理大量情况(即许多此类对象),那可能就可以了。但这当然不是理想的。
不幸的是,命名管道本身并不具有提供套接字所提供的“优雅关闭”的语义。也就是说,端点指示它们完成写入的唯一方法是断开连接(对于服务器管道)或关闭(对于服务器或客户端管道)。这两个选项都不会使管道可供读取,因此在管道上实现优美的关闭需要在应用程序协议内部进行握手,而不是依赖I / O对象。
除了这种不便(我承认,这实际上与您的问题没有直接关系)之外,还执行PipeStream.Flush()检查以查看管道是否可写。即使它无意写任何东西!这是我觉得很烦人的最后一部分,当然直接导致了您要问的问题。对于我来说,.NET Framework中的代码在那些异常带来的麻烦多于弊端的情况下,会抛出异常抛出异常,这似乎是不合理的。
综上所述,您还有其他选择:
NamedPipeServerStream和NamedPipeClientStream类型进行子类化,并重写Flush()方法,以便它实际上不执行任何操作。或更确切地说,如果您可以这样做,那将是很好。但是这些类型是sealed,所以您不能。Stream实现中。这要麻烦得多,尤其是因为您可能要覆盖所有异步成员,至少在打算在任何对I / O性能感兴趣的情况下都使用这些对象的情况下。StreamWriter自身作为关闭连接的一种方式,这将导致事物的顺序正确(即,刷新发生在关闭管道之前)。这也解决了优美的关闭问题,因为每个连接都有两个管道,您可以具有与套接字相同的基本“半关闭”语义。当然,由于难以确定哪些对管道连接彼此之间存在挑战,因此该选项非常复杂。这两个(即第二个和第三个,即实际上可能的)都具有一些明显的缺点。由于必须Stream进行所有重复的代码,因此必须拥有自己的类很痛苦。而且,将管道对象数量加倍似乎是解决异常的一种绝妙的方法(但它可能是一种可接受的且理想的实现,用于支持优美的关闭语义,并带有消除抛出异常问题的令人愉快的副作用StreamWriter.Dispose())。
请注意,在大量情况下(但是,为什么要使用管道?),频繁抛出和捕获异常可能是个问题(它们很昂贵)。因此,在那种情况下,这两种选择中的一种或另一种可能比捕获异常并且不费心关闭/处置您的代码StreamWriter(两者都会增加效率低下,从而干扰大批量情况)更可取。
| 归档时间: |
|
| 查看次数: |
3299 次 |
| 最近记录: |