Search code examples
javasocketsconnection-reset

Connection reset exception, unknown reason


I have a simple client-server program, but still I get connection reset exception. My brief research over internet/SO I could not conclude what was wrong in my code

public class SocketServer {

    public static void main (String [] args) throws Exception{
        ServerSocket ss = new ServerSocket (11060);
        Socket s = ss.accept();
        BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String str = br.readLine();
        System.out.println("Client Data :" + str);
    }
}

public class SocketClient {

    public static void main (String [] args) throws Exception{

        String ipAddress = "localhost" ;
        int port = 11060;

        Socket s = new Socket (ipAddress, port);

        String str = "Hello World";

        OutputStreamWriter osw = new OutputStreamWriter(s.getOutputStream());
        PrintWriter pw = new PrintWriter (osw);
        osw.write(str);
        osw.flush();
    }
}

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

Solution

  • You aren't closing the sockets in either the server or the client. This wil cause connection resets on some platforms.