Ошибка java socket exception

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

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.

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

In this blog, I plan to talk about some common exceptions and errors that arise while using sockets. Quite often, these socket issues arise out of application bugs, system settings, or system load. It might be an unnecessary delay to go to product teams, only to discover that the issue can be resolved by tuning/configuring your local settings. Understanding these messages will not only help resolve the issues but also make a conscious effort in avoiding these scenarios while developing applications.

I have tried to make the blog as much platform-independent as possible :). You may want to search the web if you wish to know the specifics. Though, if you are not familiar with Socket programming in Java then I also suggest you check the Java: Socket Programming Simplified, a free course on Udemy.

How to fix  java.net.SocketException: Broken pipe, Connection reset,  and Too many open files in Java?

Now, here are some common Socket related errors in Java, their explanation, and thoughts on how to solve them. 

1. java.net.SocketException: No buffer space available (maximum connections reached?)

This exception is usually observed When connections are being made at a rapid rate. This exception can arise due to one of the following conditions

a. When the number of available ephemeral network ports available for the application are nil.
b. When the system does not have enough main memory to support new connections. (Whenever a socket is created, a part of the memory is allocated for its READ/SEND buffers.. from non-paged kernel memory.)

Solution: In Windows, the number of ephemeral network ports can be increased as directed here to resolve the problem arising out of case ‘a’.

The only available solution for case ‘b’ is to make sure that the network connections are closed properly by the applications. And make sure the rate at which the connections are created does not throttle the kernel memory.

Currently, there are no formally documented approaches available to increase non-paged kernel memory. You can also see these free Java Programming courses to learn more about Socket programming in Java.

How to deal with java.net.SocketException: Broken pipe, Connection reset,  and Too many open files in Java?

2. java.net.SocketException: Broken pipe (UNIX)

A broken pipe error is seen when the remote end of the connection is closed gracefully.
Solution: This exception usually arises when the socket operations performed on either end are not synced.

3. java.net.SocketException: Connection reset [Solution]

This exception appears when the remote connection is unexpectedly and forcefully closed due to various reasons like application crashes, system reboot, the hard close of the remote host. Kernel from the remote system sends out packets with the RST bit to the local system.

The local socket on performing any SEND (could be a Keep-alive packet) or RECEIVE operations subsequently fail with this error. Certain combinations of linger settings can also result in packets with an RST bit set.

4. java.net.SocketException: Too many open files Solution

An attempt was made to open more than the maximum number of file descriptors allowed in this process. These file descriptors include various other entities along with sockets. This is implementation-dependent and could be either globally, per process, or per thread. On Linux, this is designated by the number {OPEN_MAX}.

Solution: Monitor the application and keep a watch on this. These values may be configurable on certain implementations. On Linux, ulimit can be used.

5. java.net.BindException: Address already in use: JVM_Bind/java.net.BindException: Address already in use: NET_Bind

In the case, where the exception arises while doing a socket bind. The reason is that the application is trying to bind a socket to a port/IP/protocol combination that is already in use.

Solution: Avoid this. netstat log will be of help in this case to confirm. If you want to learn more about Socket Programming in Java, I suggest you check the Java: Socket Programming Simplified, a free course on Udemy.

how to fix java.net.SocketException: Too many open files

6. java.net.BindException: Address already in use: connect

In the case, where the exception arises while doing a socket connection. There are several explanations for this some of the complex, depending on the implementation. Nonetheless, the problem can best be summarized that no local port numbers are available to the client.

This could be because there are a lot of active connections in the local system(also involves sockets in a reuse connections phenomenon).

Or a lot of ports are in TIME_WAIT state(the period between closing a connection and releasing the resources).

Solution: Increase the number of available ports. But if the problem is that there are not many concurrent active connections but in the TIME_WAIT state, then reducing the TIME_WAIT value is a solution. This is platform-dependent. Please consult the OS documents for more information.

7. Hang in Socket Write call

This happens when the sockets write buffers do not contain enough free space to accommodate the send data. This usually means the other side of the connection is not reading the data.

That’s all about the most common Socket errors and exceptions in Java applications. In this article, we have covered 7 most common Socket related errors and exceptions like Broken Pipe, Connection Reset, Too many open files, address already in use for bind and connect, and no buffer space available in Java and how to deal with them.

Содержание

  1. java.net.SocketException in Java with Examples
  2. How to Handle the Socket Exception in Java
  3. What Causes SocketException
  4. SocketException Example
  5. How to Handle SocketException
  6. Track, Analyze and Manage Errors With Rollbar
  7. Java socket connect exception
  8. Constructor Summary
  9. Method Summary
  10. Methods inherited from class java.lang.Object
  11. Constructor Detail
  12. Socket
  13. Socket
  14. Socket
  15. Socket
  16. Socket
  17. Socket
  18. Socket
  19. Socket
  20. Socket
  21. Method Detail
  22. connect
  23. connect
  24. getInetAddress
  25. getLocalAddress
  26. getPort
  27. getLocalPort
  28. getRemoteSocketAddress
  29. getLocalSocketAddress
  30. getChannel
  31. getInputStream
  32. getOutputStream
  33. setTcpNoDelay
  34. getTcpNoDelay
  35. setSoLinger
  36. getSoLinger
  37. sendUrgentData
  38. setOOBInline
  39. getOOBInline
  40. setSoTimeout
  41. getSoTimeout
  42. setSendBufferSize
  43. getSendBufferSize
  44. setReceiveBufferSize
  45. getReceiveBufferSize
  46. setKeepAlive
  47. getKeepAlive
  48. setTrafficClass
  49. getTrafficClass
  50. setReuseAddress
  51. getReuseAddress
  52. close
  53. shutdownInput
  54. shutdownOutput
  55. toString
  56. isConnected
  57. isBound
  58. isClosed
  59. isInputShutdown
  60. isOutputShutdown
  61. setSocketImplFactory
  62. setPerformancePreferences

java.net.SocketException in Java with Examples

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:

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.

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:

Источник

How to Handle the Socket Exception in Java

Table of Contents

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.

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.

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:

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:

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:

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:

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!

Источник

Java socket connect exception

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

Constructor Summary

Constructors

Modifier Constructor and Description
Socket ()

Socket (InetAddress address, int port, InetAddress localAddr, int localPort) Socket (String host, int port, InetAddress localAddr, int localPort)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type Method and Description
void bind (SocketAddress bindpoint)

void setPerformancePreferences (int connectionTime, int latency, int bandwidth)

Methods inherited from class java.lang.Object

Constructor Detail

Socket

Socket

If there is a security manager, its checkConnect method is called with the proxy host address and port number as its arguments. This could result in a SecurityException.

Examples:

  • Socket s = new Socket(Proxy.NO_PROXY); will create a plain socket ignoring any other proxy configuration.
  • Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(«socks.mydom.com», 1080))); will create a socket connecting through the specified SOCKS proxy server.

Socket

Socket

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.

If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Socket

If the application has specified a socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Socket

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.

A local port number of zero will let the system pick up a free port in the bind operation.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Socket

If the specified local address is null it is the equivalent of specifying the address as the AnyLocal address (see InetAddress.isAnyLocalAddress () ).

A local port number of zero will let the system pick up a free port in the bind operation.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Socket

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName (null) . In other words, it is equivalent to specifying an address of the loopback interface.

If the stream argument is true , this creates a stream socket. If the stream argument is false , it creates a datagram socket.

If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

If a UDP socket is used, TCP/IP related socket options will not apply.

Socket

If the stream argument is true , this creates a stream socket. If the stream argument is false , it creates a datagram socket.

If the application has specified a server socket factory, that factory’s createSocketImpl method is called to create the actual socket implementation. Otherwise a «plain» socket is created.

If there is a security manager, its checkConnect method is called with host.getHostAddress() and port as its arguments. This could result in a SecurityException.

If UDP socket is used, TCP/IP related socket options will not apply.

Method Detail

connect

connect

If the address is null , then the system will pick up an ephemeral port and a valid local address to bind the socket.

getInetAddress

If the socket was connected prior to being closed , then this method will continue to return the connected address after the socket is closed.

getLocalAddress

If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, the loopback address is returned.

getPort

If the socket was connected prior to being closed , then this method will continue to return the connected port number after the socket is closed.

getLocalPort

If the socket was bound prior to being closed , then this method will continue to return the local port number after the socket is closed.

getRemoteSocketAddress

If the socket was connected prior to being closed , then this method will continue to return the connected address after the socket is closed.

getLocalSocketAddress

If a socket bound to an endpoint represented by an InetSocketAddress is closed , then this method will continue to return an InetSocketAddress after the socket is closed. In that case the returned InetSocketAddress ‘s address is the wildcard address and its port is the local port that it was bound to.

If there is a security manager set, its checkConnect method is called with the local address and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, a SocketAddress representing the loopback address and the local port to which this socket is bound is returned.

getChannel

A socket will have a channel if, and only if, the channel itself was created via the SocketChannel.open or ServerSocketChannel.accept methods.

getInputStream

If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the input stream’s read operations will throw an IllegalBlockingModeException .

Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-

The network software may discard bytes that are buffered by the socket. Bytes that aren’t discarded by the network software can be read using read .

If there are no bytes buffered on the socket, or all buffered bytes have been consumed by read , then all subsequent calls to read will throw an IOException .

If there are no bytes buffered on the socket, and the socket has not been closed using close , then available will return 0 .

Closing the returned InputStream will close the associated socket.

getOutputStream

If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream’s write operations will throw an IllegalBlockingModeException .

Closing the returned OutputStream will close the associated socket.

setTcpNoDelay

getTcpNoDelay

setSoLinger

getSoLinger

sendUrgentData

setOOBInline

Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.

getOOBInline

setSoTimeout

getSoTimeout

setSendBufferSize

Because SO_SNDBUF is a hint, applications that want to verify what size the buffers were set to should call getSendBufferSize() .

getSendBufferSize

setReceiveBufferSize

Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.

Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call getReceiveBufferSize() .

The value of SO_RCVBUF is also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:

    For sockets accepted from a ServerSocket, this must be done by calling ServerSocket.setReceiveBufferSize(int) before the ServerSocket is bound to a local address.
  • For client sockets, setReceiveBufferSize() must be called before connecting the socket to its remote peer.
  • getReceiveBufferSize

    setKeepAlive

    getKeepAlive

    setTrafficClass

    The tc must be in the range 0 or an IllegalArgumentException will be thrown.

    For Internet Protocol v4 the value consists of an integer , the least significant 8 bits of which represent the value of the TOS octet in IP packets sent by the socket. RFC 1349 defines the TOS values as follows:

    • IPTOS_LOWCOST (0x02)
    • IPTOS_RELIABILITY (0x04)
    • IPTOS_THROUGHPUT (0x08)
    • IPTOS_LOWDELAY (0x10)

    The last low order bit is always ignored as this corresponds to the MBZ (must be zero) bit.

    Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.

    As RFC 1122 section 4.2.4.2 indicates, a compliant TCP implementation should, but is not required to, let application change the TOS field during the lifetime of a connection. So whether the type-of-service field can be changed after the TCP connection has been established depends on the implementation in the underlying platform. Applications should not assume that they can change the TOS field after the connection.

    For Internet Protocol v6 tc is the value that would be placed into the sin6_flowinfo field of the IP header.

    getTrafficClass

    As the underlying network implementation may ignore the traffic class or type-of-service set using setTrafficClass(int) this method may return a different value than was previously set using the setTrafficClass(int) method on this Socket.

    setReuseAddress

    When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.

    Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.

    When a Socket is created the initial setting of SO_REUSEADDR is disabled.

    The behaviour when SO_REUSEADDR is enabled or disabled after a socket is bound (See isBound() ) is not defined.

    getReuseAddress

    close

    Any thread currently blocked in an I/O operation upon this socket will throw a SocketException .

    Once a socket has been closed, it is not available for further networking use (i.e. can’t be reconnected or rebound). A new socket needs to be created.

    Closing this socket will also close the socket’s InputStream and OutputStream .

    If this socket has an associated channel then the channel is closed as well.

    shutdownInput

    If you read from a socket input stream after invoking this method on the socket, the stream’s available method will return 0, and its read methods will return -1 (end of stream).

    shutdownOutput

    toString

    isConnected

    Note: Closing a socket doesn’t clear its connection state, which means this method will return true for a closed socket (see isClosed() ) if it was successfuly connected prior to being closed.

    isBound

    Note: Closing a socket doesn’t clear its binding state, which means this method will return true for a closed socket (see isClosed() ) if it was successfuly bound prior to being closed.

    isClosed

    isInputShutdown

    isOutputShutdown

    setSocketImplFactory

    When an application creates a new client socket, the socket implementation factory’s createSocketImpl method is called to create the actual socket implementation.

    Passing null to the method is a no-op unless the factory was already set.

    If there is a security manager, this method first calls the security manager’s checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

    setPerformancePreferences

    Sockets use the TCP/IP protocol by default. Some implementations may offer alternative protocols which have different performance characteristics than TCP/IP. This method allows the application to express its own preferences as to how these tradeoffs should be made when the implementation chooses from the available protocols.

    Performance preferences are described by three integers whose values indicate the relative importance of short connection time, low latency, and high bandwidth. The absolute values of the integers are irrelevant; in order to choose a protocol the values are simply compared, with larger values indicating stronger preferences. Negative values represent a lower priority than positive values. If the application prefers short connection time over both low latency and high bandwidth, for example, then it could invoke this method with the values (1, 0, 0) . If the application prefers high bandwidth above low latency, and low latency above short connection time, then it could invoke this method with the values (0, 1, 2) .

    Invoking this method after this socket has been connected will have no effect.

    • Summary:
    • Nested |
    • Field |
    • Constr |
    • Method
    • Detail:
    • Field |
    • Constr |
    • Method

    Submit a bug or feature
    For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
    Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

    Источник

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

    В этом примере мы поговорим о 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. Если вы используете платный сервер и у вас закончилась подписка, то опять же у вас будет такая ошибка.
    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 lang nullpointerexception group
  • Ошибка java lang noclassdeffounderror
  • Ошибка java lang illegalargumentexception как исправить
  • Ошибка java lang classcastexception
  • Ошибка java io ioexception stalcraft

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии