package pq1; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; //java -jar GUIClient.jar localhost 8000 /** * * @author Даулет */ public class ChatServer{ //public static Vector clients = new Vector(); public static List clients = new ArrayList(); public static void main(String[] args) throws Exception { ServerSocket server = null; Socket socket; try { server = new ServerSocket(8000); System.out.println("Server is listening.."); while(true) { socket = server.accept(); clients.add(socket); SingleClient ch = new SingleClient((Socket) clients.get(clients.size() -1),clients); Thread th = new Thread(ch); th.start(); } }catch(Exception e) { e.printStackTrace(); } } } class SingleClient implements Runnable { public Socket s; public static List clients = new ArrayList(); public SingleClient(Socket s, List client) { this.s = s; clients = client; } @Override public void run() { while(true) { try { DataInputStream dis = new DataInputStream(s.getInputStream()); String data = dis.readUTF(); System.out.println(data); String[] mass = data.split("\\^"); String type = mass[0]; String alias_hostname = mass[1]; String[] mass2 = alias_hostname.split("@"); String alias = mass2[0]; String hostname = mass2[1]; switch (type) { case "j": { Date date = new Date(); data = "m^Server" + s.getInetAddress() + "^-^" + alias + " has joined from " + hostname + "[" + date + "]"; break; } case "p": { Date date = new Date(); data = "m^Server" + s.getInetAddress() + "^-^" + alias + " has departed from " + hostname + "[" + date + "]"; clients.remove(s); s.close(); } } for(Iterator i = clients.iterator(); i.hasNext();) { Socket socket = (Socket) i.next(); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF(data); } }catch(Exception e) { e.printStackTrace(); } } } } 

In the case of "p" the socket is closed, and I do not know how to make this thread in which this run method runs, close. :(

Swears on DataInputStream dis = new DataInputStream(s.getInputStream()); .

The socket is closed.

Here is the stacktrace:

 java.net.SocketException: Socket is closed at java.net.Socket.getInputStream(Socket.java:903) at pq1.SingleClient.run(ChatServer.java:61) at java.lang.Thread.run(Thread.java:745) 

    1 answer 1

    Well, you react to the exception differently, except for how to deduce its glass trace. For example, end the endless loop of the run method with return /

    • God, everywhere I tried to write return, except for catch. Thank you - Daulet Myrzan