Question

I am trying to add a restart server function that ejects all players and threads, then starts a new server socket for new players. This is how I have tried it, but when I restart, then try to add more players they don't connect?

Any help would be awesome, thanks. Alternatively, is there a way to eject all connections from server without closing socket?

private volatile ServerSocket ss;

private Socket p1;
private Socket p2;

private GameSession ses;

private ObjectOutputStream top1;
private ObjectOutputStream top2;

 public void connectToClient() {
    try {
        ss = new ServerSocket(8000);

        while (true) {


            p1 = ss.accept();

            top1 = new ObjectOutputStream(p1.getOutputStream());

            p2 = ss.accept();

            top2 = new ObjectOutputStream(p2.getOutputStream());

            see = new GameSession(p1, p2, top1, top2);

            new Thread(see).start();

        }
    } catch (IOException ex) {
        System.err.println(ex);
    }
}

private void restartServer() {
    if (ss.isBound()) {
        try {
            ss.close();
            ss = new ServerSocket(8000);

            displayLog.append(new Date() + ": Server started at socket "
                    + ss.getLocalPort() + '\n');

        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}
Was it helpful?

Solution 2

Closing the ServerSocket and creating a new one doesn't accomplish anything useful. The only effect of that would be to cause connection losses on pending, un-accepted connections. Remove that.

You have to close the accepted sockets, and have the clients react to that by attempting to reconnect.

OTHER TIPS

Your restartServer method does not contain any functionality to start a new game. All it does is create a new ServerSocket that doesn't do anything. Instead of instantiating a new ServerSocket, call connectToClientafter close.

private void restartServer() {
    if (ss.isBound()) {
        try {
            ss.close();
            connectToClient();

            displayLog.append(new Date() + ": Server started at socket "
                + ss.getLocalPort() + '\n');

        } catch (IOException ex) {
            System.err.println(ex);
        }
    }
}

Restarting a ServerSocket should work. I assume you are calling restartServer in a different Thread than connectToClient? Also ServerSocker should be volatile.

  1. Stop the thread (First hold the instance of thread) - On closure of the thread, close the client sockets first.
  2. Close the ServerSocket
  3. call connectToCLient
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top