Socket Exception: socket is closed

latata picture latata · Nov 24, 2011 · Viewed 38.4k times · Source

I want to create server which is able to be connected with multiple clients. My main function is:

ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(5556);
    } catch (IOException ex) {
        Logger.getLogger(MakaoServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    while (true) {
        try {
            Socket connection = serverSocket.accept();
            PlayerConnection playerConn = new PlayerConnection(connection);
            playerConn.start();
        } catch (IOException ex) {
            System.out.println("Nie można było utworzyć gniazda.");
        }
    }

PlayerConnection is a Thread class. The run method:

public void run() {
    InputStream input = null;
    while (true) {
        try {
            input = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            String msg = reader.readLine();
            System.out.println(msg);

        } catch (IOException ex) {
            Logger.getLogger(PlayerConnection.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

        }
    }
}

When I run client and send message to server it's received but on the next while loop iteration connection.getInputStream(); throws an Socket Exception socket is closed. Why?

java.net.SocketException: socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
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 makaoserver.PlayerConnection.run(PlayerConnection.java:38)

Answer

Sid Malani picture Sid Malani · Nov 24, 2011

Put the input stream and buffered reader outside the loop.

Possibly creating multiple stream connected to the same input stream is causing this.