Progress-servis55.ru

Новости из мира ПК
5 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java net unknownhostexception

Ошибка java.net.SocketException: Conection reset — как исправить

В этом примере мы поговорим о java.net.SocketException. Это подкласс IOException, поэтому это проверенное исключение, которое сигнализирует о проблеме при попытке открыть или получить доступ к сокету.

Настоятельно рекомендуется использовать самый «определенный» класс исключений сокетов, который более точно определяет проблему. Стоит также отметить, что SocketException, выдаётся на экран с сообщением об ошибке, которое очень информативно описывает ситуацию, вызвавшую исключение.

Простое клиент-серверное приложение

Чтобы продемонстрировать это исключение, я собираюсь позаимствовать некоторый код из клиент-серверного приложения, которое есть в java.net.ConnectException. Он состоит из 2 потоков.

  • Поток 1 — SimpleServer, открывает сокет на локальном компьютере через порт 3333. Потом он ожидает установления соединения. Если происходит соединение, он создает входной поток и считывает 1 текстовую строчку, от клиента, который был подключен.
  • Поток номер 2 — SimpleClient, подключается к сокету сервера, открытого SimpleServer. Он отправляет одну текстовую строчку.

Получается, что 2 потока будут в разных классах, запущенных двумя разными основными методами, чтобы вызвать исключение:

Как вы можете видеть, я поместил в SimpleClient 15-секундную задержку, прежде чем попытаться отправить свое сообщение. К тому моменту, когда клиент вызывает sleep(), он уже создал соединение с сервером. Я собираюсь запустить оба потока, и после того, как клиент установит соединение, я внезапно остановлю клиентское приложение.
Вот что происходит на стороне сервера:

Мы получаем исключение SocketException с сообщением «Сброс подключения». Это происходит, когда один из участников принудительно закрывает соединение без использования close().

Конечно, вы можете сделать оперативное закрытие соединения, не закрывая приложение вручную. В коде клиента, после ожидания в течение 15 секунд (или меньше), вы можете выдать новое исключение (используя throws new Exception ()), но вы должны удалить finally, иначе соединение будет нормально закрываться, и SocketException не будет сброшен.

Как решить проблему с SocketException

SocketException — это общее исключение, обозначающее проблему при попытке доступа или открытия Socket. Решение этой проблемы должно быть сделано с особой тщательностью. Вы должны всегда регистрировать сообщение об ошибке, которое сопровождает исключение.

Читать еще:  Передаточная функция ошибки

В предыдущем примере мы видели код сообщения. Это происходит, когда один из участников принудительно закрывает соединение без использования close (). Это означает, что вы должны проверить, был ли один из участников неожиданно прерван.

Также может быть сообщение «Слишком много открытых файлов», особенно если вы работаете в Linux. Это сообщение обозначает, что многие файловые дескрипторы открыты для системы. Вы можете избежать этой ошибки, если перейдете в /etc/sysctl.conf и увеличите число в поле fs.file-max. Или попытаться выделить больше стековой памяти.

Конечно, можно встретить много других сообщений. Например, «Ошибка привязки», где ваше соединение не может быть установлено, поскольку порт не может быть привязан к сокету. В этом случае проверьте, используется ли порт и т. д.
Если у вас проблема с minecraft, то в видео ниже очень просто объясняется как это решить.

Java Exception Handling – UnknownHostException

Next up in our comprehensive Java Exception Handling series we’ll be looking over the UnknownHostException. The UnknownHostException can be thrown in a variety of scenarios in which a remote connection fails due to an invalid or unknown host (i.e. IP, URL, URI, etc).

Throughout this article we’ll explore the UnknownHostException in more detail, first looking at where it sits in the overall Java Exception Hierarchy. We’ll then examine some functional code that illustrates how to establish a socket-based client/server connection, and how issues here may result in an unexpected UnknownHostException . Let’s get crackin’!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Since the UnknownHostException only occurs when dealing with some kind of IO connection, most of our sample code will illustrate a basic example of how to establish a client/server connection. Thus, let’s start by going over the simple Server class:

Читать еще:  Предельная ошибка выборочной средней формула

All the logic occurs within the CreateServer(int port) method, so let’s briefly walk through what’s going on. We start by creating a new ServerSocket instance at the specified port. Then, we create an infinite loop so we can repeat the process over and over as new clients appear. Now we await a new client connection. Once a connection is established, we create an output writer , which sends a specified message to the connected client. Since we want the client to send a message back, we next establish a reader and read from the input stream sent by the client. The sent message is then output to the console, before closing the writer and socket, and repeating the process.

Now, the client side is handled in the Client class:

Just as before, most of the logic takes place in a single method, Connect(String host, int port) . Again, we’re starting with an infinite loop so we can maintain our connection the server once established. We start by creating a new Socket to the specified host and port , then create a both a reader and writer . The reader gets the input stream sent from the server and outputs the message. We also give ourselves a few keywords ( exit and quit ) that can be used to actively disconnect from the server.

Since both the client and server scripts effectively block other threads with infinite loops, we’ll need to establish two different threads to test this. We start by executing the Server class, creating a new server:

Now we launch a new Client instance, which starts with a default connection to localhost:24601 . As the client output shows, this works fine:

As intended, the Server recognized the connection and sent a message of «Enter a message for the server.» . Now, our client side is awaiting user input in the console, so we’ll enter the sentence, «Are you alive?» :

Читать еще:  Javascript добавление строки в таблицу

The client output shows that we successfully sent our message to the server. The Server output confirms that the message was received from the Client :

Now, let’s intentionally shut down this connection to localhost:24601 by using the «quit» keyword:

This closes the existing client connection and, per our code, establishes a new connection to localhose:24601 :

Notice the slight typo in the host name. We immediately see the output showing an intention to connect, followed by a brief pause and then an expected UnknownHostException is thrown:

As mentioned in the introduction, the UnknownHostException can occur for a variety of reasons, so this is just one example. In this case, the host localhose doesn’t exist, so no connection can be established. Note that this is specifically different from other connection errors where the host simply refuses connections, or hangs and eventually produces a timeout.

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!

голоса
Рейтинг статьи
Ссылка на основную публикацию
Adblock
detector