Sap java net socketexception connection reset

Java — Socketexception: Connection Reset

I’m currently working on a small chat-program. The 2 classes I have a problem with are the classes containing the clientside and the serverside of a socket. I want the client to read the lines the server sends. I get this error:

java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) at sun.nio.cs.StreamDecoder.implRead(Unknown Source) at sun.nio.cs.StreamDecoder.read(Unknown Source) at java.io.InputStreamReader.read(Unknown Source) at java.io.BufferedReader.fill(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at MainPanel.run(MainPanel.java:121) at java.lang.Thread.run(Unknown Source) 

I read, that this happens, because the socket connection gets closed on the serverside, but I can’t see, where that happens in the code. Can someone explain, why this happens or how to fix it? Codesnippet from client:

while(true) < System.out.println("Waiting for someone to connect."); Socket currentSocket = serverSocket.accept(); System.out.println("Someone connected."); sockets.add(currentSocket); new Thread(new Runnable() < public void run() < try < while(true) < BufferedReader br = new BufferedReader(new InputStreamReader(currentSocket.getInputStream())); String input = br.readLine(); for(Socket socket : sockets) < PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); pw.println(input); >> > catch(Exception ex) < sockets.remove(currentSocket); System.out.println("One connection lost."); >> >).start(); > 

Источник

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

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

В этом примере мы поговорим о 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(); >> > > >
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

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

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

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

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

Если у вас проблема с minecraft, то чтобы решить проблему попробуйте сделать следующее:

  1. Обновите джаву, скачайте по ссылке https://www.java.com/ru/download/ новую версию и установите;
  2. Возможно блокирует антивирус или брандмауэр. Отключите антивирус и добавьте minecraft в список исключения в брандмауэре (или его можно выключить на время).
  3. При запуске игры, в правом нижнем углу отображается версия игры, если у вас не последняя версия, то обновите.
  4. Если у вас много расширений и модов, то это может приводить к багам, удалите последние установленные моды – это может решить проблему.
  5. Если вы используете платный сервер и у вас закончилась подписка, то опять же у вас будет такая ошибка.
Читайте также:  Таблица

Средняя оценка 2.1 / 5. Количество голосов: 104

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

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 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 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.

Do you have stack traces from both sides? Can you describe the network architecture a bit more? (Over the wild Internet? On the same machine? Somewhere in between?) Does it happen all the time? Or intermittently?

15 Answers 15

There are several possible causes.

  1. 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.
  2. 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.
  3. It can also be caused by closing a socket when there is unread data in the socket receive buffer.
  4. 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.

@MattLyons Thanks. There are much better MSDN articles than that. Frankly I find that one hard to believe. A connection won’t even exist until the correct source and target IP addresses have been established. The MSDN articles I have seen refer to persistent network errors timing out the connection.

@AlanTelles And as usual when plagiarists paraphrase they introduce errors. I didn’t say anything about the port not being open, which would not cause this exception; and the part about the socket being closed is wrong as well.

Читайте также:  Все для программиста на c sharp

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.

Источник

SocketException: Connection Reset when trying to read from socket in Java?

Having some irritating trouble with Java sockets, my application seems to be failing at a very basic level. Part of my application requires writing filenames across a TCP connection. The receiver code is as follows:

ServerSocket serverSocket = new ServerSocket(4445); Socket socket = serverSocket.accept(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); String filename = reader.readLine(); 
 Socket socket = new Socket(InetAddress.getLocalHost(), 4445); PrintWriter writer = new PrintWriter(socket.getOutputStream()); writer.write("Test.jpg"); 

Very, very basic stuff here, but for some reason, I’m getting a SocketException: Connection Reset when I run this? This is the full stack trace:

Exception in thread "main" java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at sun.nio.cs.StreamDecoder.readBytes(Unknown Source) at sun.nio.cs.StreamDecoder.implRead(Unknown Source) at sun.nio.cs.StreamDecoder.read(Unknown Source) at java.io.InputStreamReader.read(Unknown Source) at java.io.BufferedReader.fill(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at java.io.BufferedReader.readLine(Unknown Source) at FileReceiver.main(FileReceiver.java:11) 

with the FileReceiver.java:11 line being the one where the reader.readLine() call is made. I can’t for the life of me figure out what is going wrong, similarly basic use of TCP sockets has always worked for me in the past, why is this happening now?

Источник

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