0

I'm programming a server which can connect with multiple clients. A function to accept the clients runs in its own thread. ServerSocket.accept() blocks the code until a client connects. So how can I stop the thread, while its still waiting for clients?

// Main
public static void main(String[] args) {
    // Start the thread
    ConnectServer conServer = new ConnectServer();

    // Stop the thread    
    try {
        Thread.sleep(500);
        conServer.stop();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

// Class ConnectServer
public class ConnectServer implements Runnable {
private boolean exit = false;
private Thread t = null;
public List<Socket> socketList = new ArrayList<Socket>();

public ConnectServer() {
    t = new Thread(this);
    exit = false;
    t.run();
}

// Execution of the thread starts in the run() - method
@Override
public void run() {
    System.out.println("Starting listener");
    while (!exit) {
        connectClient();
    }
    System.out.println("Listener stopped.");
}

private void connectClient() {
    try {
        ServerSocket listener = new ServerSocket(4444);
        Socket client = listener.accept(); // Blocked until a client connects
        socketList.add(client);
        listener.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// To stop the Thread
public void stop() {
    exit = true;
}
Filburt
  • 17,626
  • 12
  • 64
  • 115

0 Answers0