Java 关闭套接字和 ObjectOutputStream 的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/654117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to close a socket and ObjectOutputStream?
提问by Ben Page
I am writing a networked application in Java, to communicate between the client and the server I am using serialized objects to represent data/commands and sending them through object output/input streams.
我正在用 Java 编写一个网络应用程序,以在客户端和服务器之间进行通信我使用序列化对象来表示数据/命令并通过对象输出/输入流发送它们。
I am having problems cleanly closing the connections, I assume that I am missing something fundamental that I do not really know about, I've never used sockets with serialization before.
我在干净地关闭连接时遇到了问题,我认为我错过了一些我并不真正了解的基本知识,我以前从未使用过带有序列化的套接字。
What ever order I try to shutdown the connection (close client first, close server first) a ConnectionReset
exception is thrown. I cannot catch this exception as the client runs in another thread to the rest of the program constantly listening for messages, this must be done, as in Java socket.read()
is a blocking method.
我尝试关闭连接(先关闭客户端,先关闭服务器)的任何命令ConnectionReset
都会引发异常。我无法捕获此异常,因为客户端在另一个线程中运行,而程序的其余部分不断地侦听消息,必须这样做,因为在 Java 中socket.read()
是一种阻塞方法。
What is the correct way to close a socket that I am using to send objects?
关闭用于发送对象的套接字的正确方法是什么?
采纳答案by Jason Day
You need to send your listener (whether client or server, it doesn't matter) some kind of signal to stop listening for more data. Here is a very simple example:
您需要向您的侦听器(无论是客户端还是服务器,都无所谓)发送某种信号以停止侦听更多数据。这是一个非常简单的例子:
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));
while (true) {
Object obj = ois.readObject();
if (obj instanceof String) {
if ((String)obj).equalsIgnoreCase("quit")) {
break;
}
}
// handle object
}
ois.close();
sock.close();
回答by Avi
You should probably not be waiting to read() from a socket, while the other end is closing it. In a good network protocol, the client can inform the server that it has nothing more to write (maybe by sending it a special close character) before closing the connection.
您可能不应该等待从套接字读取(),而另一端正在关闭它。在一个好的网络协议中,客户端可以在关闭连接之前通知服务器它没有什么可写的(可能通过向它发送一个特殊的关闭字符)。
回答by sspkiet
you can implement a protocol of yours over the TCP/IP protocol. Header part of the packets using this protocol will signify different types of packets like- connection packet, data packet, close-connection packet etc.
您可以通过 TCP/IP 协议实现您的协议。使用该协议的数据包的报头部分将表示不同类型的数据包,如连接数据包、数据包、关闭连接数据包等。
回答by user207421
ObjectInputStream.readObject()
will throw EOFException
if the peer has finished sending objects and closed the connection. You must be ignoring it.
ObjectInputStream.readObject()
EOFException
如果对等方已完成发送对象并关闭连接,则将抛出。你一定忽略了它。