内容导读:
连接超时(Connection Timed Out):
- 定义: 客户端在尝试连接服务器时,如果在一定时间内未成功连接,会抛出
ConnectionException
,提示“连接超时”。 - 原因:
- 远程主机的指定端口没有服务监听。
- 远程主机不接受连接。
- 远程主机不可用。
- 网络连接慢。
- 没有到达远程主机的转发路径。
读取超时(Read Timed Out):
- 定义:
InputStream
的read()
方法在读取数据时会阻塞,如果在指定时间内没有读取到数据,会抛出InterrupedIOException
,提示“读取超时”。 - 原因:
- 客户端: 服务器响应慢或主机离线。
- 服务器: 读取数据时间超过预设超时时间。
如果你没有显式设置连接超时,系统将依赖操作系统或网络设备的默认超时设置。
操作系统默认不会为读取操作设置超时时间,也就是说,读取操作(如读取网络套接字的数据)在没有显式设置超时时间的情况下,可能会无限期地阻塞,直到有数据可读或发生错误。
1. Introduction
In this tutorial, we’ll focus on the timeout exceptions of Java socket programming. Our goal is to understand why these exceptions occur, and how to handle them.
2. Java Sockets and Timeouts
A socket is one end-point of a logical link between two computer applications. In other words, it’s a logical interface that applications use to send and receive data over the network.
In general, a socket is a combination of an IP address and a port number. Each socket is assigned a specific port number that’s used to identify the service.
Connection-based services use TCP-based stream sockets. For this reason, Java provides the java.net.Socket class for client-side programming. Conversely, server-side TCP/IP programming makes use of the java.net.ServerSocket class.
Another type of socket is the UDP-based datagram socket, which is used for connectionless services. Java provides