Java net socketexception catch

java.net.SocketException – How to solve SocketException

In this example we are going to talk about java.net.SocketException . This is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket.

As you might already know, it’s strongly advised to use the most “specific” socket exception class that designates the problem more accurately. It is also worth noting that SocketException , usually comes with an error message that is very informative about the situation that caused the exception.

1. A simple Client-Server Application

To demonstrate this exception, I’m going to borrow some code from the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It consists of 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. This time though the two threads will be in different classes launched by two different main methods, so as to cause a SocketEception :

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(); >> > > >
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(); >> > > >

As you can see, I’ve put a 15 second delay in SimpleClient for the client to wait before attempting to its message. It is important to notice that by the time the client calls sleep() , he has already created the connection to the server. What I’m going to do is start both threads and after the client makes the connection I will suddenly stop the client application.

Читайте также:  Arrow with div css

Here’s what happens on the server side:

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)

As you can see we get a SocketException with the message Connection reset . This happens when on of the participants “violently” closes the connection without using close() . Of course you can provoke a “violent” close of the connection without having to close the application manually. In the client code, after waiting for 15 seconds (or less), you can throw a new exception (using throws new Exception() ), but you have to remove the finally clause or else then the connection will close normally and no SocketException will be thrown.

2. How to solve SocketException

As we’ve already mentioned, SocketException is a general exception the designates a problem when trying to access or open a Socket . So as you can imagine, solving that problem has to be done with extra care. You shall always log the error message that accompanies the exception. In the previous example we’ve seen the message code>Connection reset . This happens when on of the participants “violently” closes the connection without using close() . This means that you should check whether one of the participants has terminated unexpectedly. One slightly bizarre message can be Too many open files , especially when you run on Linux. This message designates that to many file descriptors are open to the system. You can avoid that error if you go to /etc/sysctl.conf and raise the number in fs.file-max field. Additionally, you can try to give more stack memory.

Читайте также:  Reshape matrix in python

Of course many other messages can be met. For example «Bind error» , where your connection cannot be established because the port cannot be bind to the socket. In that case check if the port is already in use etc.

In the next few example we are going to look deeper into the subclass of SocketException to get a better understanding of it.

Download Source Code

This was an example on java.net.SocketException and how to solve SocketException . You can download the source code of this example here: SocketExceptionExample.zip

Источник

Catching exceptions caused by temporary network errors

I have to download some URLs, and it can happen that during the operations some exception may occur, like java.net.NoRouteToHostException . I consider it a temporary error exception, as the download can succeed if you retry it after some time.
So, I’d like to catch all those exceptions related to temporary errors, and I’ve started with these: java.net.NoRouteToHostException , java.net.SocketException
Can you list other exceptions like these?

java.net.SocketException is the parent of java.net.NoRouteToHostException so you could maybe catch only the parent. The others childs of SocketException are BindException, ConnectException and PortUnreachableException. Maybe it’s ok to catch only SocketException in your case.

4 Answers 4

java.net.SocketException is the parent of java.net.NoRouteToHostException so you could maybe catch only the parent. The others childs of SocketException are BindException , ConnectException and PortUnreachableException . Maybe it’s ok to catch only SocketException in your case.

One pattern which is sometimes useful for dealing with transitory errors on retry-able operations is to define an error-callback interface and some classes that implement it; when an error occurs, let the callback object know, and let it decide whether an exception should be thrown or the action should be retried. Because the existing communications classes don’t follow such a pattern, it may be necessary to catch their exceptions and turn them into callbacks.

Note that this approach allows much cleaner handling of many error-handling scenarios than would normal exception handling. Among other things, it makes it easy to set policies for how many retries may be attempted, how long they may take, etc. and also provides a means of skipping future retries if something like a «cancel» request is received.

As @reef has already said java.net.NoRouteToHostException exntends java.net.SocketException, so if you catch java.net.SocketException it is enough. But java.net.SocketException extends IOException and I think that this is what you really should to catch. All IO problems should throw this exception.

HttpRetryException is another. Maybe everything in java.net that does not extend SocketException?

One quick (and very dirty) way could be

Источник

Как обрабатывать Java SocketException

Узнайте, что вызывает SocketException в Java и как с ним справиться.

1. введение

В этом кратком руководстве мы рассмотрим причины возникновения SocketException на примере.

Мы также, конечно, обсудим, как справиться с этим исключением.

2. Причины исключения SocketException

Наиболее распространенной причиной SocketException является запись или чтение данных в закрытое сокет соединение или из него. Еще одна причина этого-закрытие соединения перед чтением всех данных в буфере сокета.

Давайте подробнее рассмотрим некоторые общие причины.

2.1. Медленная сеть

Основной проблемой может быть плохое сетевое соединение. Установка более высокого таймаута соединения сокета может уменьшить скорость SocketException для медленных соединений:

socket.setSoTimeout(30000); // timeout set to 30,000 ms

2.2. Вмешательство брандмауэра

Сетевой брандмауэр может закрывать соединения сокетов. Если у нас есть доступ к брандмауэру, мы можем отключить его и посмотреть, решит ли он проблему.

В противном случае мы можем использовать инструмент мониторинга сети, такой как Wireshark для проверки активности брандмауэра.

2.3. Длительное Простое Соединение

Простаивающие соединения могут быть забыты на другом конце (для экономии ресурсов). Если мы должны использовать соединение в течение длительного времени, мы можем отправлять сообщения heartbeat , чтобы предотвратить состояние ожидания.

2.4. Ошибка приложения

И последнее, но не менее важное: SocketException может возникнуть из-за ошибок или ошибок в нашем коде.

Чтобы продемонстрировать это, давайте запустим сервер на порту 6699:

SocketServer server = new SocketServer(); server.start(6699);

Когда сервер будет запущен, мы будем ждать сообщения от клиента:

serverSocket = new ServerSocket(port); clientSocket = serverSocket.accept(); out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String msg = in.readLine();

Как только мы его получим, мы ответим и закроем соединение:

out.println("hi"); in.close(); out.close(); clientSocket.close(); serverSocket.close();

Итак, допустим, клиент подключается к нашему серверу и посылает “привет”:

SocketClient client = new SocketClient(); client.startConnection("127.0.0.1", 6699); client.sendMessage("hi");

Но, если клиент отправляет другое сообщение:

client.sendMessage("hi again");

Поскольку клиент отправляет “привет снова” на сервер после прерывания соединения, возникает SocketException .

3. Обработка исключения SocketException

Обработка SocketException довольно проста и понятна. Подобно любому другому проверенному исключению, мы должны либо выбросить его, либо окружить блоком try-catch.

Давайте рассмотрим исключение в нашем примере:

try < client.sendMessage("hi"); client.sendMessage("hi again"); >catch (SocketException e)

Здесь мы закрыли клиентское соединение после того, как произошло исключение. Повторная попытка не сработает, потому что соединение уже закрыто. Вместо этого мы должны начать новую связь:

client.startConnection("127.0.0.1", 6699); client.sendMessage("hi again");

4. Заключение

В этой статье мы рассмотрели, что вызывает SocketException и как с этим справиться.

Источник

Оцените статью