1

I am trying to make a chat program with multiple clients and I need to find a way to handle when clients disconnect. I have tried to use isConnected() but that didn't work. If you can help me, thank you in advance.

Here is my java code:

import java.io.*;
import java.net.*;
import java.util.ArrayList;

public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
    public void run() {
        try {
            server = new ServerSocket(55555, 100);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true) {
            try {
                s = server.accept();
                users.add(s);
                outputs.add(new ObjectOutputStream(s.getOutputStream()));
                new EchoThread(s).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            newUser();
        }
    }
}
public class EchoThread extends Thread {
    public EchoThread(Socket s) throws IOException {
    }
    public void run() {
        }
    }
public void newUser() {
    try {
        for(ObjectOutputStream o: outputs) {
                o.writeObject(s.getInetAddress() + " Connected");
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
server() throws IOException {
    Thread t = new Thread(new Accept());
    t.start();
    }
public static void main(String[] args) throws IOException {
    new server();
}
}
mardis7021
  • 61
  • 1
  • 1
  • 6
  • Thanks for the question - I hope it will be answered soon. I did some minor, cosmetic changes in your question - improved a bit text formatting, placed couple of comas a and dot, so it's easier to understand and read the question. Take care! – jjczopek Dec 04 '15 at 21:50
  • i want to do it with multiple clients not just 1 – mardis7021 Dec 04 '15 at 22:47
  • Don't do I/O in the accept thread. The ObjectOutputStream should be created in the run() method of the connection-handling thread. – user207421 Dec 04 '15 at 23:00

0 Answers0