Ошибка java socket exception

The SocketException is an exception in Java that is thrown to indicate that an error was encountered while creating or accessing a Socket.

Since the SocketException is a checked exception, it either needs to be thrown or surrounded by a try-catch block in code.

What Causes SocketException

SocketException is a subclass of IOException and is the most general exception that indicates a problem when trying to open or access a socket. Some common causes for the SocketException are:

  • Closed socket connection — The most common cause of SocketException is reading or writing from or to a closed socket connection. It can also occur when the connection is closed before all the data is read in the socket buffer.
  • Slow network — A poor network connection might also cause a SocketException. Setting a higher connection timeout can decrease the rate of SocketException for slow connections.
  • Network firewall — A network firewall can close socket connections. A network monitoring tool like Wireshark can be used to check firewall activities.
  • Idle connection — Long idle connections might also cause a SocketException. If a connection needs to be used for a long time, heartbeat messages can be sent to prevent the idle state.
  • Errors in code — A SocketException can also occur because of issues or bugs in code. For example, if a client sends a message to the server after the socket connection is closed.

SocketException Example

The following is an example of a SocketException thrown when trying to write to a closed socket connection. Two classes, MyServer and MyClient are created to illustrate this.

MyServer.java:

public class MyServer {
    public static void main(String[] args) throws InterruptedException {
        new Thread(new Server()).start();
    }

    static class Server implements Runnable {
        @Override
        public void run() {
            ServerSocket serverSocket = null;

            try {
                serverSocket = new ServerSocket(4444);

                while (true) {
                    try {
                        Socket clientSocket = serverSocket.accept();

                        BufferedReader inputReader = new BufferedReader(
                                new InputStreamReader(clientSocket.getInputStream()));
                        System.out.println("Message from client: " + inputReader.readLine());
                    } catch (SocketTimeoutException ste) {
                        ste.printStackTrace();
                    }
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (serverSocket != null) {
                        serverSocket.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

Executing MyServer.main() starts a new Server thread, which creates a ServerSocket object on port 4444. The server socket accepts incoming connections on that port, creates an InputStreamReader object from the input stream coming from the client socket, then reads and prints the message sent by the client. A continuous while loop is used to await the connection and print the message received from the client.

MyClient.java:

public class MyClient {
    public static void main(String[] args) {
        new Thread(new Client()).start();
    }

    static class Client implements Runnable {
        @Override
        public void run() {
            Socket socket = null;

            try {
                socket = new Socket("localhost", 4444);

                PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
                outWriter.println("Hello");

                outWriter.close();
                socket.close();

                outWriter = new PrintWriter(socket.getOutputStream(), true);
                outWriter.println("Hello again");
            } catch (UnknownHostException uhe) {
                uhe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

The MyClient.main() method above starts a Client thread, which creates a Socket instance and connects to the server host (localhost) and port (4444) defined earlier. A PrintWriter object is then created using the socket output stream to send a message to the server. This works fine and the message is printed by the server:

Message from client: Hello

The socket is then closed and another PrintWriter object is attempted to be created using the closed socket’s output stream. However, since the socket is closed, writing to it is not possible. Therefore, a SocketException is thrown:

java.net.SocketException: Socket is closed
    at java.net.Socket.getOutputStream(Socket.java:943)
    at MyClient$Client.run(MyClient.java:26)
    at java.lang.Thread.run(Thread.java:748)

How to Handle SocketException

Since SocketException is a checked exception, it can be handled by surrounding it with a try-catch block. The MyClient class in the earlier example can be updated to handle the exception:

public class MyClient {
    public static void main(String[] args) {
        new Thread(new Client()).start();
    }

    static class Client implements Runnable {
        @Override
        public void run() {
            Socket socket = null;

            try {
                socket = new Socket("localhost", 4444);

                PrintWriter outWriter = new PrintWriter(socket.getOutputStream(), true);
                outWriter.println("Hello");

                outWriter.close();
                socket.close();

                try {
                    outWriter = new PrintWriter(socket.getOutputStream(), true);
                } catch (SocketException se) {
                    if (socket.isClosed()) {
                        socket = new Socket("localhost", 4444);
                        outWriter = new PrintWriter(socket.getOutputStream(), true);
                    }
                }

                outWriter.println("Hello again");
            } catch (UnknownHostException uhe) {
                uhe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}

In the above example, the code that can throw the SocketException is surrounded in a try-catch block. In case a SocketException occurs when attempting to write to the socket, it is caught in the catch block and the socket instance is created and connected again to the server host and port. The PrintWriter object is also created again using the new socket output stream to send the second message to the server. This works successfully and both messages are now printed by the server:

Message from client: Hello
Message from client: Hello again

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

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.lang.Object
     java.lang.Throwable
         java.lang.Exception
             java.io.IOException
                 java.net.SocketException

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.

Implemented Interfaces: Serializable
Direct Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException

What is socket programming?

It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network. Sockets provide an interface to establish communication using the network protocol stack and enable programs to share messages over the network. Sockets are endpoints in network communications. A socket server is usually a multi-threaded server that can accept socket connection requests. A socket client is a program/process that initiates a socket communication request.

java.net.SocketException: Connection reset
 

This SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received. TCP RST packet is that the remote side telling you the connection on which the previous TCP packet is sent is not recognized, maybe the connection has closed, maybe the port is not open, and something like these. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags.

Now as of implementation it is clear that we need two programs one handling the client and the other handling the server. They are as follows: 

Example 1: Server-side 

Java

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

                }

            }

        }

    }

}

Example 2: Client-side 

Java

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

                }

            }

        }

    }

}

Output:

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)

Now in order to get rid off of the java.net.SocketException to get proper output then it can be perceived via as if you are a client and getting this error while connecting to the server-side application then append the following changes as follows:

  1. First, check if the Server is running by doing telnet on the host port on which the server runs.
  2. Check if the server was restarted
  3. Check if the server failed over to a different host
  4. log the error
  5. Report the problem to the server team

Note: In most cases, you will find that either server is not running or restarted manually or automatically.

Last Updated :
12 Nov, 2021

Like Article

Save Article

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

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

SimpleClientApp.java:

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 – это общее исключение, обозначающее проблему при попытке доступа или открытия Socket. Решение этой проблемы должно быть сделано с особой тщательностью. Вы должны всегда регистрировать сообщение об ошибке, которое сопровождает исключение.

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

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

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

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

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

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.

Socket clientSocket = ServerSocket.accept();
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
int readed = is.read(); // WHERE ERROR STARTS !!!

The interesting thing is for my JAVA Socket if a client connects to my ServerSocket and close its connection without sending anything is.read() is being called repeatedly.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;

while(true)
{
  Receive();
}

Then you get a stackTrace something like below on and on

java.net.SocketException: Socket is closed
    at java.net.ServerSocket.accept(ServerSocket.java:494)

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

String Receive() throws Exception
{
try {                   
            int readed = is.read();
           ....
}catch(Exception e)
{
        tryReConnect();
        logit(); //etc
}


//...
}

This reestablises my connection for unknown client socket losts

private void tryReConnect()
        {
            try
            {
                ServerSocket.close();
                //empty my old lost connection and let it get by garbage col. immediately 
                clientSocket=null;
                System.gc();
                //Wait a new client Socket connection and address this to my local variable
                clientSocket= ServerSocket.accept(); // Waiting for another Connection
                System.out.println("Connection established...");
            }catch (Exception e) {
                String message="ReConnect not successful "+e.getMessage();
                logit();//etc...
            }
        }

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

  1. the java.net.SocketException in Java
  2. Causes of the java.net.SocketException: Connection reset in Java
  3. Reproduce the java.net.SocketException: Connection reset Error and Identify Its Causes in Java
  4. Fix the java.net.SocketException: Connection reset Error in Java

Fix the Java.Net.SocketException: Connection Reset in Java

Today’s article will discuss the reasons for and solutions for the java.net.SocketException: Connection reset error that might occur in Java. Finally, we will see how we can eradicate Java’s java.net.SocketException: Connection reset error.

the java.net.SocketException in Java

SocketException is the subclass of IOException. Its status as a checked exception is guaranteed.

When attempting to open or access a socket, the most generic exception that can occur indicates that there is an issue. You will get the following error if you look at the server’s side:

java.net.SocketException: Connection reset

Causes of the java.net.SocketException: Connection reset in Java

java.net.SocketException: Connection reset is thrown on the server when the client terminates the connection to the socket before the response can be sent back through the socket. Let’s suppose you may close the browser before the response is fetched from the server.

TCP RST packets are the remote side’s way of informing you that the connection on which the last TCP packet was transmitted is not acknowledged. A Connection reset indicates that a TCP RST was successfully received.

This could be because the connection is no longer active. After all, the port is closed or for other reasons.

A simple definition of a Reset packet contains no content and has the RST bit set in the TCP header flags. The following are some of the reasons the java.net.SocketException: Connection reset error can occur:

  1. As a result of receiving a close command from a remote system, the TCP socket has been closed.
  2. This can also be caused by a high amount of requests being queued by the server, which causes the request to be timed-out before the client can view it. You can also check the server’s health and logs to see whether a heavy load is caused.
  3. Closing a socket with unread data in the socket receive buffer can also result in this error.
  4. The connection has been intentionally reset on the other end. While this is rare and inappropriate for application software, commercial software is not uncommon.
  5. Either the application protocol is incorrect, or you tried to write to a connection that had been terminated before you were finished.

Reproduce the java.net.SocketException: Connection reset Error and Identify Its Causes in Java

Example Code (Server.java file):

package com.demobrokenpipe;

import java.net.*;
import java.io.*;

public class Server {
  public static void main(String[] args) throws Exception{
    ServerSocket socket = new ServerSocket(6666);
    System.out.println("The Server Is Initialized");
    Socket conn = socket.accept();
    System.out.println("A Request Is Received");
    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(conn.getInputStream()));
    System.exit(1);
    conn.close();
  }
}

Example Code (Client.java file):

package com.demobrokenpipe;

import java.net.*;
import java.io.*;

public class Client {
    public static void main(String argv[]) throws Exception {
        Socket socket = new Socket("localhost", 6666);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.write("Hi");
        System.out.println("Incorrect String");
        BufferedReader bufferReader = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        System.out.println(bufferReader.read());
    }
}

Here, we have two classes, Server.java and Client.java, connecting to the port number 6666. We open two terminals and run both files to communicate between client and server, but it prints a message and an error as follows.

Error Description:

Incorrect String
Exception in thread "main" java.net.SocketException: Connection reset

Let’s understand the error by going through the Socket, SocketException, and SocketException: Connectin reset that will lead to the causes of this error.

We use sockets to make a successful connection in two or more programs to communicate with each other using the same network. In our case, we have two programs, Client.java and Server.java.

By using Sockets, we get an interface to communicate via network protocol stack and let the programs share messages over the same network.

In simple words, we can say that Sockets are the endpoints in communications over a network. Usually, the socket server is multi-threaded that can accept socket connection requests sent by different clients.

The SocketException is the child class of IOException, so it is a checked exception. It occurs when we try to access or open the socket. Have a look at the complete exception hierarchy for SocketException errors.

Full Exception Hierarchy:

Fix Java Net SocketException Connection Reset in java - exception hierarchy

Whenever the client closes the socket connection, it results in SocketException on the server-side because the response was not returned over that socket yet. Yes, you got it right.

We get the java.net.SocketException: Connection reset error on the server side when the client closes the socket connection before receiving the response fully.

Here, Connection reset means the remote endpoint informs you that the connection on which the last TCP packet was sent is not recognized. There can be various reasons for this.

Let’s find them below:

  1. The user closes the web browser before getting the response completely.

  2. Most commonly, the connection we try to write has been closed normally. We can also say that there is an application protocol error.

  3. Another possibility is that the required port is not open anymore. We also see this error when a client closes the socket while unread data is still in a socket receive buffer.

  4. If you are a Windows user, you may find it as software caused a connection abort. The newbies make it confused with Connection reset.

    Remember, both are not the same. The software caused a connection abort occurs when we have some network issues while sending from our end.

  5. Another situation is using a method of Java Socket called setSoTimeout() that enables/disables the SO_TIMEOUT option by passing a timeout value which must be greater than 0. Passing 0 is also a reason that results in the SocketException: Connection Reset error.

Now, the point is that are we also closing the connection in the Client.java file? Let’s find that below.

Fix the java.net.SocketException: Connection reset Error in Java

If we face this error as a client while connecting with the server, we can fix this by doing any of the following:

  1. Make sure the server runs via telnet on a host port. This port is where the server runs.
  2. Confirm if a server is restarted.
  3. Assess if the same server fails over to a different host.

Further, we can move towards the solution if we overcome the reasons described in the previous section. In our case, removing System.exit(1) fixed the error because it was exiting the system and closing the program.

Example Code (Server.java file):

import java.net.*;
import java.io.*;

public class Server {
  public static void main(String[] args) throws Exception{
    ServerSocket socket = new ServerSocket(6666);
    System.out.println("The Server Is Initialized");
    Socket conn = socket.accept();
    System.out.println("A Request Is Received");
    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(conn.getInputStream()));
    System.out.println(reader.readLine());
    conn.close();
  }
}

Example Code (Client.java file):

import java.net.*;
import java.io.*;

public class Client {
    public static void main(String argv[]) throws Exception {
        Socket socket = new Socket("localhost", 6666);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.write("Hi");
        System.out.println("Incorrect String");
        BufferedReader bufferReader = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        System.out.println(bufferReader.read());
    }
}

Понравилась статья? Поделить с друзьями:
  • Ошибка java security cert
  • Ошибка java runtime environment not found
  • Ошибка java net socket timeout
  • Ошибка java lang unsatisfiedlinkerror
  • Ошибка java lang numberformatexception