I am getting below error when I am trying to connect to a TCP server. My programs tries to open around 300-400 connections using diffferent threads and this is happening during 250th thread. Each thread uses its own connection to send and receive data.
java.net.SocketException: Connection timed out:could be due to invalid address
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:372)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:233)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:220)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:385)
Here is the code I have that a thread uses to get socket:
socket = new Socket(my_hostName, my_port);
Is there any default limit on number of connections that a TCP server can have at one time? If not how to solve this type of problems?
asked Aug 3, 2010 at 19:11
2
You could be getting a connection timeout if the server has a ServerSocket bound to the port you are connecting to, but is not accepting the connection.
If it always happens with the 250th connection, maybe the server is set up to only accept 250 connections. Someone has to disconnect so you can connect. Or you can increase the timeout; instead of creating the socket like that, create the socket with the empty constructor and then use the connect() method:
Socket s = new Socket();
s.connect(new InetSocketAddress(my_hostName, my_port), 90000);
Default connection timeout is 30 seconds; the code above waits 90 seconds to connect, then throws the exception if the connection cannot be established.
You could also set a lower connection timeout and do something else when you catch that exception…
answered Aug 3, 2010 at 19:29
ChochosChochos
5,16522 silver badges26 bronze badges
1
Why all the connections? Is this a test program? In which case be aware that opening large numbers of connections from a single client stresses the client in ways that aren’t exercised by real systems with large numbers of different client hosts, so test results from that kind of client aren’t all that valid. You could be running out of client ports, or some other client resource.
If it isn’t a test program, same question. Why all the connections? You’d be better off running a connection pool and reusing a much smaller number of connections serially. The network only has so much bandwidth after all; dividing it by 400 isn’t very useful.
answered Aug 4, 2010 at 4:24
Methods declared in class java.lang.Object
Constructor Detail
Socket
Socket
If there is a security manager, its checkConnect method is called with the proxy host address and port number as its arguments. This could result in a SecurityException.
Examples:
- Socket s = new Socket(Proxy.NO_PROXY); will create a plain socket ignoring any other proxy configuration.
- Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(«socks.mydom.com», 1080))); will create a socket connecting through the specified SOCKS proxy server.
Socket
Socket
If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.
If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.
If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.
Socket
If the application has specified a socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.
If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.
Socket
If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.
A local port number of zero will let the system pick up a free port in the bind operation.
If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.
Socket
If the specified local address is null it is the equivalent of specifying the address as the AnyLocal address (see InetAddress.isAnyLocalAddress () ).
A local port number of zero will let the system pick up a free port in the bind operation.
If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.
Socket
If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.
If the stream argument is true , this creates a stream socket. If the stream argument is false , it creates a datagram socket.
If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.
If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.
If a UDP socket is used, TCP/IP related socket options will not apply.
Socket
If the stream argument is true , this creates a stream socket. If the stream argument is false , it creates a datagram socket.
If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.
If there is a security manager, its checkConnect method is called with host.getHostAddress() and port as its arguments. This could result in a SecurityException.
If UDP socket is used, TCP/IP related socket options will not apply.
Method Detail
connect
connect
If the address is null , then the system will pick up an ephemeral port and a valid local address to bind the socket.
getInetAddress
If the socket was connected prior to being closed , then this method will continue to return the connected address after the socket is closed.
getLocalAddress
If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, the loopback address is returned.
getPort
If the socket was connected prior to being closed , then this method will continue to return the connected port number after the socket is closed.
getLocalPort
If the socket was bound prior to being closed , then this method will continue to return the local port number after the socket is closed.
getRemoteSocketAddress
If the socket was connected prior to being closed , then this method will continue to return the connected address after the socket is closed.
getLocalSocketAddress
If a socket bound to an endpoint represented by an InetSocketAddress is closed , then this method will continue to return an InetSocketAddress after the socket is closed. In that case the returned InetSocketAddress ‘s address is the wildcard address and its port is the local port that it was bound to.
If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, a SocketAddress representing the loopback address and the local port to which this socket is bound is returned.
getChannel
A socket will have a channel if, and only if, the channel itself was created via the SocketChannel.open or ServerSocketChannel.accept methods.
getInputStream
If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the input stream’s read operations will throw an IllegalBlockingModeException .
Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-
The network software may discard bytes that are buffered by the socket. Bytes that aren’t discarded by the network software can be read using read .
If there are no bytes buffered on the socket, or all buffered bytes have been consumed by read , then all subsequent calls to read will throw an IOException .
If there are no bytes buffered on the socket, and the socket has not been closed using close , then available will return 0 .
Closing the returned InputStream will close the associated socket.
getOutputStream
If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream’s write operations will throw an IllegalBlockingModeException .
Closing the returned OutputStream will close the associated socket.
setTcpNoDelay
getTcpNoDelay
setSoLinger
getSoLinger
sendUrgentData
setOOBInline
Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.
getOOBInline
setSoTimeout
getSoTimeout
setSendBufferSize
Because SO_SNDBUF is a hint, applications that want to verify what size the buffers were set to should call getSendBufferSize() .
getSendBufferSize
setReceiveBufferSize
Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.
Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call getReceiveBufferSize() .
The value of SO_RCVBUF is also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:
- For sockets accepted from a ServerSocket, this must be done by calling ServerSocket.setReceiveBufferSize(int) before the ServerSocket is bound to a local address.
- For client sockets, setReceiveBufferSize() must be called before connecting the socket to its remote peer.
getReceiveBufferSize
setKeepAlive
getKeepAlive
setTrafficClass
The tc must be in the range 0 or an IllegalArgumentException will be thrown.
For Internet Protocol v4 the value consists of an integer , the least significant 8 bits of which represent the value of the TOS octet in IP packets sent by the socket. RFC 1349 defines the TOS values as follows:
- IPTOS_LOWCOST (0x02)
- IPTOS_RELIABILITY (0x04)
- IPTOS_THROUGHPUT (0x08)
- IPTOS_LOWDELAY (0x10)
The last low order bit is always ignored as this corresponds to the MBZ (must be zero) bit.
Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.
As RFC 1122 section 4.2.4.2 indicates, a compliant TCP implementation should, but is not required to, let application change the TOS field during the lifetime of a connection. So whether the type-of-service field can be changed after the TCP connection has been established depends on the implementation in the underlying platform. Applications should not assume that they can change the TOS field after the connection.
For Internet Protocol v6 tc is the value that would be placed into the sin6_flowinfo field of the IP header.
getTrafficClass
As the underlying network implementation may ignore the traffic class or type-of-service set using setTrafficClass(int) this method may return a different value than was previously set using the setTrafficClass(int) method on this Socket.
setReuseAddress
When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.
Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.
When a Socket is created the initial setting of SO_REUSEADDR is disabled.
The behaviour when SO_REUSEADDR is enabled or disabled after a socket is bound (See isBound() ) is not defined.
getReuseAddress
close
Any thread currently blocked in an I/O operation upon this socket will throw a SocketException .
Once a socket has been closed, it is not available for further networking use (i.e. can’t be reconnected or rebound). A new socket needs to be created.
Closing this socket will also close the socket’s InputStream and OutputStream .
If this socket has an associated channel then the channel is closed as well.
shutdownInput
If you read from a socket input stream after invoking this method on the socket, the stream’s available method will return 0, and its read methods will return -1 (end of stream).
shutdownOutput
toString
isConnected
Note: Closing a socket doesn’t clear its connection state, which means this method will return true for a closed socket (see isClosed() ) if it was successfuly connected prior to being closed.
isBound
Note: Closing a socket doesn’t clear its binding state, which means this method will return true for a closed socket (see isClosed() ) if it was successfuly bound prior to being closed.
isClosed
isInputShutdown
isOutputShutdown
setSocketImplFactory
When an application creates a new client socket, the socket implementation factory’s createSocketImpl method is called to create the actual socket implementation.
Passing null to the method is a no-op unless the factory was already set.
If there is a security manager, this method first calls the security manager’s checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.
setPerformancePreferences
Sockets use the TCP/IP protocol by default. Some implementations may offer alternative protocols which have different performance characteristics than TCP/IP. This method allows the application to express its own preferences as to how these tradeoffs should be made when the implementation chooses from the available protocols.
Performance preferences are described by three integers whose values indicate the relative importance of short connection time, low latency, and high bandwidth. The absolute values of the integers are irrelevant; in order to choose a protocol the values are simply compared, with larger values indicating stronger preferences. Negative values represent a lower priority than positive values. If the application prefers short connection time over both low latency and high bandwidth, for example, then it could invoke this method with the values (1, 0, 0) . If the application prefers high bandwidth above low latency, and low latency above short connection time, then it could invoke this method with the values (0, 1, 2) .
Invoking this method after this socket has been connected will have no effect.
setOption
getOption
supportedOptions
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2022, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Источник
- Sockets in Java
- Timeouts in Java
- Causes of
java.net.SocketTimeoutException: Connection timed outin Java - Solution to
java.net.SocketTimeoutException: Connection timed outin Java

In today’s article, we will discuss java.net.SocketTimeoutException: Connection timed out. But first, let’s take a closer look at the concepts of sockets and timeouts.
Sockets in Java
A logical link between two computer applications might have multiple endpoints, one of which is a socket.
To put it another way, it is a logical interface that applications use to transmit and receive data over a network. An IP address and a port number comprise a socket in its most basic form.
A unique port number is allotted to each socket, which is utilized to identify the service. Connection-based services use stream sockets that are based on TCP.
Because of this, Java offers the java.net.Socket class as a client-side programming option.
On the other hand, the java.net.ServerSocket class is utilized in server-side TCP/IP programming. The datagram socket based on UDP is another kind of socket, and it’s the one that’s employed for connectionless services.
Java supports java.net.DatagramSocket for UDP operations.
Timeouts in Java
An instance of a socket object is created when the socket constructor is called, allowing a connection between the client and the server from the client side.
As input, the constructor expects to receive the address of the remote host and the port number. After that, it tries to use the parameters provided to establish a connection to the remote host.
The operation will prevent other processes from proceeding until a successful connection is created. But, the application will throw the following error if the connection is not successful after a specified time.
java.net.SocketTimeoutException: Connection timed out
Listening to incoming connection requests, the ServerSocket class on the server side is permanently active. When a connection request is received by ServerSocket, the accept function is invoked to create a new socket object.
Similar to the previous method, this one blocks until the remote client is connected.
Causes of java.net.SocketTimeoutException: Connection timed out in Java
The following are some possible reasons for the error.
- The server is operating fine. However, the
timeoutvalue is set for a shorter time. Therefore, increase the value of thetimeout. - On the remote host, the specified port is not being listened to by any services.
- There is no route to the remote host being sent.
- The remote host does not appear to be allowing any connections.
- There is a problem reaching the remote host.
- Internet connection that is either slow or unavailable.
Solution to java.net.SocketTimeoutException: Connection timed out in Java
We can pre-set the timeout option for client and server activities. Adding the try and catch constructs would be an appropriate solution.
-
On the client side, the first thing we’ll do is construct a null
socket. Following that, we will use theconnect()method and then configure thetimeoutparameter where the timeout should be larger than 0 milliseconds.If the timeout expires before the function returns,
SocketTimeoutExceptionis thrown.Socket s = new Socket(); SocketAddress sAdres = new InetSocketAddress(host, port); s.connect(sAdres, 50000); -
If you want to set a
timeoutvalue from the server side, you can use thesetSoTimeout()function. The value of thetimeoutparameter determines the length of time that theServerSocket.accept()function will block.ServerSocket servers = new new ServerSocket(port); servers.setSoTimeout(10000);Similarly, the
timeoutshould be more than 0 milliseconds. If thetimeoutexpires before the method returns, the method will generate aSocketTimeoutException. -
Determining a connection timeout and then handling it afterward using a
try-catchblock is yet another excellent technique to deal withHttpException.HttpUrlConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(8000);
In this example we are going to talk about java.net.SocketTimeoutException. This exception is a subclass of java.io.IOException, so it is a checked exception.
From the javadoc we read that this exception :” Signals that a timeout has occurred on a socket read or accept”. That means that this exception emerges when a blocking operation of the two, an accept or a read, is blocked for a certain amount of time, called the timeout. Let’s say that the socket is configured with a timeout of 5 seconds.
If either the accept() or read() method, blocks for more than 5 seconds, a SocketTimeoutException is thrown, designating that a timeout has occurred. It is important to note that after this exception is thrown. the socket remains valid, so you can retry the blocking call or do whatever you want with the valid socket.
1. A simple Cilent-Server application
To demonstrate this exception, I’m going to use the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It creates two threads. The first one, SimpleServer, opens a socket on the local machine on port 3333. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient, attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it.
SocketTimeoutExceptionExample.java:
package com.javacodegeeks.core.net.unknownhostexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class SocketTimeoutExceptionExample {
public static void main(String[] args) {
new Thread(new SimpleServer()).start();
new Thread(new SimpleClient()).start();
}
static class SimpleServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(3333);
serverSocket.setSoTimeout(7000);
while (true) {
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client said :" + inputReader.readLine());
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (serverSocket != null)
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
static class SimpleClient implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
Thread.sleep(3000);
socket = new Socket("localhost", 3333);
PrintWriter outWriter = new PrintWriter(
socket.getOutputStream(), true);
outWriter.println("Hello Mr. Server!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket. Additionally, you will notice that in SimpleServer I’ve specified the timeout to be of 7 seconds using this method : serverSocket.setSoTimeout(7000);.
So, what we expect to happen here, is the communication to finish normally because the client will connect to the server after 3 seconds. That’s 4 seconds before the timeout barrier is reached. If you run the program, you will see this output:
Client said :Hello Mr. Server!
That means that the client, successfully connected to the server and achieved to transmit its text. Now if you wait a bit more, you will see that a
1. An example of SocketTimeoutException
Now, if you keep the above program running, after the Client said :Hello Mr. Server! message is transmitted successfully, you will notice that a SocketTimeoutExceptionis thrown:
Client said :Hello Mr. Server! java.net.SocketTimeoutException: Accept timed out at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method) at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135) at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198) at java.net.ServerSocket.implAccept(ServerSocket.java:530) at java.net.ServerSocket.accept(ServerSocket.java:498) at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:35) at java.lang.Thread.run(Thread.java:744)
That’s because, after the SimpleServer serves the first client, it loops back to the accept() method to serve the next client in line, but no one is connected. So, when the time out is reached, SocketTimeoutException is thrown.
Of course, you can choose to handle this exception differently. For example , you can choose to loop back to the accept method, even if the exception is thrown, because the socket remains valid.
In the next example, I will launch two client threads with a certain delay between them, so that one of them sends its message before any exception occurs. The other client thread sends its message after an exception is thrown. Let’s see how you can do that, and pay attention to the server thread:
SocketTimeoutExceptionExample.java:
package com.javacodegeeks.core.net.unknownhostexception;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class SocketTimeoutExceptionExample {
public static void main(String[] args) throws InterruptedException {
new Thread(new SimpleServer()).start();
new Thread(new SimpleClient()).start();
Thread.sleep(20000);
new Thread(new SimpleClient()).start();
}
static class SimpleServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(3333);
serverSocket.setSoTimeout(7000);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client said :"+ inputReader.readLine());
} catch (SocketTimeoutException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class SimpleClient implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
Thread.sleep(3000);
socket = new Socket("localhost", 3333);
PrintWriter outWriter = new PrintWriter(
socket.getOutputStream(), true);
outWriter.println("Hello Mr. Server!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Now if you run the program for a while you will notice that every seven seconds a SocketTimeoutException is thrown :
Client said :Hello Mr. Server! java.net.SocketTimeoutException: Accept timed out at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method) at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135) at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198) at java.net.ServerSocket.implAccept(ServerSocket.java:530) at java.net.ServerSocket.accept(ServerSocket.java:498) at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38) at java.lang.Thread.run(Thread.java:744) java.net.SocketTimeoutException: Accept timed out at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method) at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135) at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198) at java.net.ServerSocket.implAccept(ServerSocket.java:530) at java.net.ServerSocket.accept(ServerSocket.java:498) at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38) at java.lang.Thread.run(Thread.java:744) Client said :Hello Mr. Server! java.net.SocketTimeoutException: Accept timed out at java.net.DualStackPlainSocketImpl.waitForNewConnection(Native Method) at java.net.DualStackPlainSocketImpl.socketAccept(DualStackPlainSocketImpl.java:135) at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:398) at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:198) at java.net.ServerSocket.implAccept(ServerSocket.java:530) at java.net.ServerSocket.accept(ServerSocket.java:498) at com.javacodegeeks.core.net.unknownhostexception.SocketTimeoutExceptionExample$SimpleServer.run(SocketTimeoutExceptionExample.java:38) at java.lang.Thread.run(Thread.java:744) ... ... ...
So as you can see even after the exception is thrown, the socket remains active and receives a message form the second client thread. The above program will keep throwing a SocketTimeoutException every seven seconds.
3. How to Solve SocketTimeoutException
In the above example we’ve shown what causes a SocketTimeoutException in the case of the accept(). The same principles will apply in the case of read(). Now, what can you do to avoid that exception. If the server side application is under your control, you should try yo adjust the timeout barrier so that its more flexible on network delays. You should surely consider doing that especially when your server application will run in a remote machine. Other than that, you can check whatever causes delays in your network, a malfunctioning router etc.
Download Source Code
This was an example on java.net.SocketTimeoutException and how to solve SocketTimeoutException. You can download the source code of this example here : SocketTimeoutExceptionExample.zip
Сразу сообщу, что если у вас проблема с игрой майнкрафт, то листайте в самый конец статьи, а пока информация для разработчиков и программистов.
В этом примере мы поговорим о java.net.SocketException. Это подкласс IOException, поэтому это проверенное исключение, которое сигнализирует о проблеме при попытке открыть или получить доступ к сокету.
Настоятельно рекомендуется использовать самый «определенный» класс исключений сокетов, который более точно определяет проблему. Стоит также отметить, что SocketException, выдаётся на экран с сообщением об ошибке, которое очень информативно описывает ситуацию, вызвавшую исключение.
Простое клиент-серверное приложение
Чтобы продемонстрировать это исключение, я собираюсь позаимствовать некоторый код из клиент-серверного приложения, которое есть в java.net.ConnectException. Он состоит из 2 потоков.
- Поток 1 – SimpleServer, открывает сокет на локальном компьютере через порт 3333. Потом он ожидает установления соединения. Если происходит соединение, он создает входной поток и считывает 1 текстовую строчку, от клиента, который был подключен.
- Поток номер 2 – SimpleClient, подключается к сокету сервера, открытого SimpleServer. Он отправляет одну текстовую строчку.
Получается, что 2 потока будут в разных классах, запущенных двумя разными основными методами, чтобы вызвать исключение:
package com.javacodegeeks.core.socketecxeption;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class SimpleServerApp {
public static void main(String[] args) throws InterruptedException {
new Thread(new SimpleServer()).start();
}
static class SimpleServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(3333);
serverSocket.setSoTimeout(0);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Client said :"+ inputReader.readLine());
} catch (SocketTimeoutException e) {
e.printStackTrace();
}
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
SimpleClientApp.java:
package com.javacodegeeks.core.socketecxeption;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SimpleClientApp {
public static void main(String[] args) {
new Thread(new SimpleClient()).start();
}
static class SimpleClient implements Runnable {
@Override
public void run() {
Socket socket = null;
try {
socket = new Socket("localhost", 3333);
PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Wait");
Thread.sleep(15000);
outWriter.println("Hello Mr. Server!");
}catch (SocketException e) {
e.printStackTrace();
}catch (InterruptedException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Как вы можете видеть, я поместил в SimpleClient 15-секундную задержку, прежде чем попытаться отправить свое сообщение. К тому моменту, когда клиент вызывает sleep(), он уже создал соединение с сервером. Я собираюсь запустить оба потока, и после того, как клиент установит соединение, я внезапно остановлю клиентское приложение.
Вот что происходит на стороне сервера:
java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:196) at java.net.SocketInputStream.read(SocketInputStream.java:122) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177) at java.io.InputStreamReader.read(InputStreamReader.java:184) at java.io.BufferedReader.fill(BufferedReader.java:154) at java.io.BufferedReader.readLine(BufferedReader.java:317) at java.io.BufferedReader.readLine(BufferedReader.java:382) at com.javacodegeeks.core.lang.NumberFormatExceptionExample. SimpleServerApp$SimpleServer.run(SimpleServerApp.java:36) at java.lang.Thread.run(Thread.java:744)
Мы получаем исключение SocketException с сообщением «Сброс подключения». Это происходит, когда один из участников принудительно закрывает соединение без использования close().
Конечно, вы можете сделать оперативное закрытие соединения, не закрывая приложение вручную. В коде клиента, после ожидания в течение 15 секунд (или меньше), вы можете выдать новое исключение (используя throws new Exception ()), но вы должны удалить finally, иначе соединение будет нормально закрываться, и SocketException не будет сброшен.
SocketException – это общее исключение, обозначающее проблему при попытке доступа или открытия Socket. Решение этой проблемы должно быть сделано с особой тщательностью. Вы должны всегда регистрировать сообщение об ошибке, которое сопровождает исключение.
В предыдущем примере мы видели код сообщения. Это происходит, когда один из участников принудительно закрывает соединение без использования close(). Это означает, что вы должны проверить, был ли один из участников неожиданно прерван.
Также может быть сообщение «Слишком много открытых файлов», особенно если вы работаете в Linux. Это сообщение обозначает, что многие файловые дескрипторы открыты для системы. Вы можете избежать этой ошибки, если перейдете в /etc/sysctl.conf и увеличите число в поле fs.file-max. Или попытаться выделить больше стековой памяти.
Конечно, можно встретить много других сообщений. Например, «Ошибка привязки», где ваше соединение не может быть установлено, поскольку порт не может быть привязан к сокету. В этом случае проверьте, используется ли порт и т. д.
Если у вас проблема с minecraft, то чтобы решить проблему попробуйте сделать следующее:
- Обновите джаву, скачайте по ссылке https://www.java.com/ru/download/ новую версию и установите;
- Возможно блокирует антивирус или брандмауэр. Отключите антивирус и добавьте minecraft в список исключения в брандмауэре (или его можно выключить на время).
- При запуске игры, в правом нижнем углу отображается версия игры, если у вас не последняя версия, то обновите.
- Если у вас много расширений и модов, то это может приводить к багам, удалите последние установленные моды – это может решить проблему.
- Если вы используете платный сервер и у вас закончилась подписка, то опять же у вас будет такая ошибка.