Java net socketexception connection reset что делать

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

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

SocketException

SocketException 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. The full exception hierarchy of this error is:

Java socket exceptions

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 .

java.net.SocketException: Connection reset

I am getting the following error trying to read from a socket. I’m doing a readInt() on that InputStream , and I am getting this error. Perusing the documentation this suggests that the client part of the connection closed the connection. In this scenario, I am the server.

I have access to the client log files and it is not closing the connection, and in fact its log files suggest I am closing the connection. So does anybody have an idea why this is happening? What else to check for? Does this arise when there are local resources that are perhaps reaching thresholds?

I do note that I have the following line:

just prior to the readInt() . There is a reason for this (long story), but just curious, are there circumstances under which this might lead to the indicated error? I have the server running in my IDE, and I happened to leave my IDE stuck on a breakpoint, and I then noticed the exact same errors begin appearing in my own logs in my IDE.

Anyway, just mentioning it, hopefully not a red herring. 🙁

There are several possible causes.

The other end has deliberately reset the connection, in a way which I will not document here. It is rare, and generally incorrect, for application software to do this, but it is not unknown for commercial software.

Читайте также:  Программы для дизайна интерьера

More commonly, it is caused by writing to a connection that the other end has already closed normally. In other words an application protocol error.

It can also be caused by closing a socket when there is unread data in the socket receive buffer.

In Windows, ‘software caused connection abort’, which is not the same as ‘connection reset’, is caused by network problems sending from your end. There’s a Microsoft knowledge base article about this.

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can’t process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn’t listening.

In other cases, an intervening firewall or even the remote host itself might “forget” about your TCP connection. This could happen if you don’t send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.

Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException . This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you’ll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

Читайте также:  Русификация программ с помощью Multilizer

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

Embarrassing to say it, but when I had this problem, it was simply a mistake that I was closing the connection before I read all the data. In cases with small strings being returned, it worked, but that was probably due to the whole response was buffered, before I closed it.

In cases of longer amounts of text being returned, the exception was thrown, since more then a buffer was coming back.

You might check for this oversight. Remember opening a URL is like a file, be sure to close it (release the connection) once it has been fully read.

You should inspect full trace very carefully,

I’ve a server socket application and fixed a java.net.SocketException: Connection reset case.

In my case it happens while reading from a clientSocket Socket object which is closed its connection because of some reason. (Network lost,firewall or application crash or intended close)

Actually I was re-establishing connection when I got an error while reading from this Socket object.

The interesting thing is for my JAVA Socket if a client connects to my ServerSocket and close its connection without sending anything is.read() calls itself recursively.It seems because of being in an infinite while loop for reading from this socket you try to read from a closed connection.
If you use something like below for read operation;

Then you get a stackTrace something like below on and on

What I did is just closing ServerSocket and renewing my connection and waiting for further incoming client connections

This reestablises my connection for unknown client socket losts

I couldn’t find another way because as you see from below image you can’t understand whether connection is lost or not without a try and catch ,because everything seems right . I got this snapshot while I was getting Connection reset continuously.

enter image description here

I had the same error. I found the solution for problem now. The problem was client program was finishing before server read the streams.

Читайте также:  Программы для подсчета калорий

I had this problem with a SOA system written in Java. I was running both the client and the server on different physical machines and they worked fine for a long time, then those nasty connection resets appeared in the client log and there wasn’t anything strange in the server log. Restarting both client and server didn’t solve the problem. Finally we discovered that the heap on the server side was rather full so we increased the memory available to the JVM: problem solved! Note that there was no OutOfMemoryError in the log: memory was just scarce, not exhausted.

I also had this problem with a Java program trying to send a command on a server via SSH. The problem was with the machine executing the Java code. It didn’t have the permission to connect to the remote server. The write() method was doing alright, but the read() method was throwing a java.net.SocketException: Connection reset. I fixed this problem with adding the client SSH key to the remote server known keys.

Прекращена работа программы Java(TM) Platform SE binary

Если не работает Minecraft или другая программа, пользователь может видеть ошибку «Прекращена работа программы Java(TM) Platform SE binary».

Выявим ее источник:

  • Появление ошибки после первого запуска приложения свидетельствует о возможном отсутствии модуля Джава на ПК. Даже если есть какие-то следы ПО, то их лучше удалить и скачать плагин заново.
  • Если Джава установлена на компьютере, сравните ее разрядность с аналогичным параметром операционной системы. Для этого найдите плагин в панели управления. Название, не содержащее цифр, говорит о версии x64, в противном случае установлена x32.

После исключения отсутствия модуля или несовместимости остается только один источник проблемы – видеокарта. Выполните следующие действия:

  1. Создайте новую переменную среды. О том, как это сделать, рассказано выше. Напишите следующие параметры: имя – _JAVA_OPTIONS, значение – -Xmx256M.
  2. Сохраните переменную, перейдите к настройкам в игре.
  3. Отключите следующие параметры: VSync, VBos, Smooth Lighting.
  4. FOV должно иметь значение Normal.

Для закрепления результата обновите драйвера для видеокарты и перезагрузите компьютер.

Ссылка на основную публикацию