4

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)
latata
  • 1,703
  • 5
  • 27
  • 57
  • Your read loop should terminate when `readLine()` returns `null`. At present you will get an endless stream of `null` messages when the peer closes the connection. – user207421 Feb 01 '16 at 01:02

2 Answers2

6

Put the input stream and buffered reader outside the loop.

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

Sid Malani
  • 2,078
  • 1
  • 13
  • 13
  • But I want to get more than one message from client. If you put input stream and buffered reader outside the loop I will only get one message. – latata Nov 24 '11 at 22:59
  • No once you have a handle to the input stream you don't need to keep initialising it. Your readline will still be in the loop to collect messages. – Sid Malani Nov 24 '11 at 23:00
  • Can you remove the logger and put a e.printStackTrace and print the trace here – Sid Malani Nov 24 '11 at 23:07
  • I think your client is closing connection. Nothing seems wrong with server code. Can you also paste your client code? You still need to move the input stream buffered reader initial out of the loop – Sid Malani Nov 24 '11 at 23:14
  • Creating multiple streams does not cause this problem. Closing them does. – user207421 Nov 02 '17 at 09:53
0

try

public void run() {
    InputStream input = null;
    input = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(input));

    while (true) {
        try {
            String msg = reader.readLine();
            System.out.println(msg);
        } catch (IOException ex) {
            Logger.getLogger(PlayerConnection.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

        }
    }
}

Also don't forget to close sockets when your done with them

try {
  // Create objects
  // do stuff
} finally {
  if (obj != null) obj.close();
}
David Waters
  • 11,979
  • 7
  • 41
  • 76
  • I've done it but I still get the same exception. – latata Nov 24 '11 at 23:06
  • You said that the connection closed exception was thrown on the connection.getInputStream() in the second pass through the loop. this line is no longer in the loop, where is the exception being thrown now? Also could you please show some of the code from PlayerConnection as you might be closing the connection from the server side. – David Waters Nov 24 '11 at 23:11
  • 1
    I solved the issue. :) I was opening also an OutputStream it caused exception. – latata Nov 24 '11 at 23:18
  • @latata, why opening an `OutputStream` caused the socket to get closed? – AlikElzin-kilaka Sep 12 '13 at 20:02
  • This code will spin forever at end of stream. It need a null check on the result of `readLine()`. – user207421 Nov 21 '15 at 22:35