Socket Exception: socket is closed

I want to create a server that can connect to multiple clients. My main function:

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. 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 start the client and send a message to the server, it is accepted, but on the next while loop iteration connection.getInputStream (); throws a socket exception exception. 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) 
+4
source share
2 answers

Place the input stream and the buffered reader outside the loop.

It is possible to create multiple streams connected to the same input stream.

+6
source

to 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 remember to close the sockets when you are done with them

 try { // Create objects // do stuff } finally { if (obj != null) obj.close(); } 
0
source

Source: https://habr.com/ru/post/1382970/


All Articles