当前位置: 动力学知识库 > 问答 > 编程问答 >

sockets - How to restart a serverSocket in java

问题描述:

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);

}

}

}

网友答案:

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.

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: