Socketexception java что это

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

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

1. введение

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Пока все идет хорошо.

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

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

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

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

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

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

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

Источник

How to Handle Java SocketException

Last modified: December 31, 2020

1. Introduction

In this quick tutorial, we’ll learn the causes of SocketException with an example.

We’ll also, of course, discuss how to handle the exception.

2. Causes of SocketException

The most common cause of SocketException is writing or reading data to or from a closed socket connection. Another cause of it is closing the connection before reading all data in the socket buffer.

Let’s take a closer look at some common underlying reasons.

2.1. Slow Network

A poor network connection might be the underlying problem. Setting a higher socket connection timeout can decrease the rate of SocketException for slow connections:

2.2. Firewall Intervention

A network firewall can close socket connections. If we have access to the firewall, we can turn it off and see if it solves the problem.

Otherwise, we can use a network monitoring tool such as Wireshark to check firewall activities.

2.3. Long Idle Connection

Idle connections might get forgotten by the other end (to save resources). If we have to use a connection for a long time, we can send heartbeat messages to prevent idle state.

2.4. Application Error

Last but not least, SocketException can occur because of mistakes or bugs in our code.

To demonstrate this, let’s start a server on port 6699:

When the server is started, we’ll wait for a message from the client:

Once we get it, we’ll respond and close the connection:

So, let’s say a client connects to our server and sends “hi”:

But, if the client sends another message:

Since the client sends “hi again” to the server after the connection is aborted, a SocketException occurs.

3. Handling of a SocketException

Handling SocketException is pretty easy and straightforward. Similar to any other checked exception, we must either throw it or surround it with a try-catch block.

Let’s handle the exception in our example:

Here, we’ve closed the client connection after the exception occurred. Retrying won’t work, because the connection is already closed. We should start a new connection instead:

4. Conclusion

In this article, we had a look at what causes SocketException and how to handle it.

As always, the code is available over on Github.

Источник

Socket Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown to indicate that there is an error creating or accessing a Socket.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs a new SocketException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs a new SocketException with no detail message.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable)Class(Inherited from Throwable)Handle

The handle to the underlying Android instance.

(Inherited from Throwable)JniIdentityHashCode(Inherited from Throwable)JniPeerMembersLocalizedMessage

Creates a localized description of this throwable.

Returns the detail message string of this throwable.

(Inherited from Throwable)PeerReference(Inherited from Throwable)StackTrace(Inherited from Throwable)ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable)Dispose()(Inherited from Throwable)Dispose(Boolean)(Inherited from Throwable)FillInStackTrace()

Fills in the execution stack trace.

Initializes the cause of this throwable to the specified value.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Sets the Handle property.

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable)ToString()(Inherited from Throwable)UnregisterFromRuntime()(Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed()(Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced()(Inherited from Throwable)
IJavaPeerable.Finalized()(Inherited from Throwable)
IJavaPeerable.JniManagedPeerState(Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32)(Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates)(Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference)(Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

java.net.SocketException: сброс соединения

У меня есть доступ к файлам журнала клиента, и он не закрывает соединение, и фактически его файлы журнала предполагают, что я закрываю соединение. Так у кого-нибудь есть идея, почему это происходит? Что еще проверить? Возникает ли это, когда есть локальные ресурсы, которые, возможно, достигают порогов?

Я отмечаю, что у меня есть следующая строка:

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

Есть несколько возможных причин.

Другой конец намеренно сбросил соединение, что я не буду здесь описывать. Это редко, и вообще неправильно, прикладное программное обеспечение делает это, но это не неизвестно для коммерческого программного обеспечения.

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

Это также может быть вызвано закрытием сокета, когда в буфере приема сокета есть непрочитанные данные.

В Windows «программный сбой соединения прерван», что не совпадает с «сбросом соединения», вызвано сетевыми проблемами отправки с вашего конца. Об этом есть статья в базе знаний Microsoft.

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

В других случаях промежуточный брандмауэр или даже удаленный хост может «забыть» о вашем TCP подключении. Это может произойти, если вы не отправляете какие-либо данные в течение длительного времени (общее время ожидания составляет 2 часа) или потому, что узел был перезагружен и потерял информацию об активных соединениях. Отправка данных по одному из этих несуществующих соединений также вызовет RST.

Обновление в ответ на дополнительную информацию:

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

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

В тех случаях, когда возвращалось большее количество текста, генерировалось исключение, так как возвращалось больше буфера.

Вы можете проверить это упущение. Помните, что открытие URL-адреса похоже на файл, обязательно закройте его (освободите соединение), как только оно будет полностью прочитано.

Вы должны тщательно проверить полный след,

У меня есть приложение сокета сервера и исправлено Java.net.SocketException: Connection reset случай.

На самом деле я восстанавливал соединение, когда у меня возникла ошибка при чтении с этого объекта Socket.

Затем вы получаете stackTrace что-то вроде ниже и дальше

Я просто закрыл ServerSocket и обновил свое соединение, а также ожидал дальнейших входящих клиентских соединений.

Это восстанавливает мое соединение для неизвестных потерь сокета клиента

Socketexception java что это. T75Ul. Socketexception java что это фото. Socketexception java что это-T75Ul. картинка Socketexception java что это. картинка T75Ul

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

У меня была эта проблема с системой SOA, написанной на Java. Я работал и на клиенте, и на сервере на разных физических машинах, и они долгое время работали нормально, затем эти неприятные сбросы подключения появились в журнале клиента, и в журнале сервера не было ничего странного. Перезапуск клиента и сервера не решил проблему. Наконец, мы обнаружили, что куча на стороне сервера была довольно полной, поэтому мы увеличили объем памяти, доступной для JVM: проблема решена! Обратите внимание, что в журнале не было OutOfMemoryError: памяти было недостаточно, не было исчерпано.

Источник

Java Exception Handling – SocketException

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.

This code sample also uses the Logging utility class, the source of which can be found here on GitHub.

When Should You Use It?

To illustrate how a SocketException can commonly occur we’ll start with a simple client/server configuration, similar to that we used in a previous post. We run the test by running both the client and server on separate threads, then the server will prompt the client to enter a message. Once the client enters a message, that value is transferred to and received by the server, before the server then prompts for a new message. This repeats until the client gracefully ends the connection.

We’ll start by looking at the Server.java class:

Meanwhile, here’s the Client.java class:

And the client outputs after entering “Hello” at the prompt:

Everything is working as expected. But, what happens if we interrupt the client connection in some way, such as terminating the process? Immediately the server experiences a problem and catches the thrown SocketException :

This shouldn’t be much of a surprise that closing the client connection produces an error on the server. However, what happens if we reverse the process and terminate the server process while connected? As it happens, the client prompt remains open and awaits input from the user, due to these code statements:

Execution halts while awaiting for user input. However, as soon as a message is entered the client recognizes that the server has disconnected, so the client now throws a SocketException when execution resumes:

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! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

Socketexception java что это. erron hello. Socketexception java что это фото. Socketexception java что это-erron hello. картинка Socketexception java что это. картинка erron hello

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *