[英]Why does the “Close” call on a stream behave differently in C# and in Java?
Consider the following scenario, a servlet has been written in Java and once you connect to the servlet, it starts writing to the OutputStream, let's say 10 million bytes, 1 byte at a time.考虑以下场景,在 Java 中编写了一个 servlet,一旦连接到该 servlet,它就开始写入 OutputStream,比如说 1000 万字节,一次 1 个字节。
You have a client program which reads the servlet's response stream and reads say 100 bytes and calls close.您有一个客户端程序,它读取 servlet 的响应 stream 并读取 100 个字节并调用 close。 Now if your client program is in Java, the streams close immediately and the server stops sending the content, but if the client program is in C#, the close call takes a long time to finish because it apparently waits for server to finish writing all the 10 million bytes.现在,如果您的客户端程序在 Java 中,则流立即关闭并且服务器停止发送内容,但是如果客户端程序在 C# 中,则关闭调用需要很长时间才能完成,因为它显然是在等待服务器完成所有1000 万字节。
So, I have two questions on this,所以,我对此有两个问题,
Any pointers will be greatly appreciated:-)任何指针将不胜感激:-)
I'm assuming sockets of some kind here.我假设 sockets 在这里。 I would suspect that the Java implementation is simply closing the client socket, possibly causing an error on the server, whilst the C# version is being slightly more friendly to the server and waiting for it to acknowledge a close request.我怀疑 Java 实现只是关闭客户端套接字,可能会导致服务器出错,而 C# 版本对服务器稍微友好并等待它确认关闭请求。 Since the server is busy firing off data, it doesn't get - or at least doesn't process - the close request until it's finished sending.由于服务器正忙于发送数据,因此在完成发送之前它不会获得 - 或至少不处理 - 关闭请求。
Think of it this way: somebody at your front door trying to sell you something and won't be interrupted.可以这样想:有人在您的前门试图向您推销一些东西并且不会被打断。 You can slam the door in their face which shuts them up immediately, or you can wait until they've finished talking and then ask them to leave.你可以当着他们的面关上门,让他们立刻关上门,或者你可以等到他们说完再让他们离开。
To solve it, perhaps you could create a worker thread that opens the stream, waits for the 100 bytes, then closes.为了解决这个问题,也许您可以创建一个工作线程来打开 stream,等待 100 个字节,然后关闭。 In the meantime your program can do whatever it needs to do while the thread eventually shuts down.与此同时,当线程最终关闭时,您的程序可以做它需要做的任何事情。
So, I finally figured this out a couple of weeks back and verified it with Microsoft as well.所以,我终于在几周前弄清楚了这一点,并与微软进行了验证。 The difference between C# and Java is the fact that in Java close call closes the request/connection as well, while in C#, it doesn't happen unless you follow it up with an xxxRequest.Abort() call. The difference between C# and Java is the fact that in Java close call closes the request/connection as well, while in C#, it doesn't happen unless you follow it up with an xxxRequest.Abort() call. Hope this helps someone else as well.希望这对其他人也有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.