質問

私はJavaにネットワークサーバーを書いています、そしてそれに小さな問題があります。 コードが話してみましょう:

import java.io.IOException;
import java.net.ServerSocket;
/**
* Another flavor of the server module.
* According to GOD (also known as Joshua Bloch) this is the proper
* implementation of a singleton (Note: serialization).
* 
* @author estol
*/
public enum EnumSingletonServer implements ServerInterface, Runnable
{
    SERVER;
    private ServerSocket serverSocket = null;
    private boolean Listening         = true;

    @Override
    public void bind() {
        this.bind(DEFAULTPORT);
    }

    @Override
    public void bind(int Port) {
        try {
            this.serverSocket = new ServerSocket(Port);
        } catch (IOException ioe) {
            System.err.printf("Cannot bind to port %d\nAdditional information:\n%s\nExiting\n", Port, ioe.getMessage());
            System.exit(1);
        }
    }

    /**
    * Not that elegant, but does not work with flipping the switch, because
    * the loop (in public void run()) is only running when there is an incoming connection(?).
    * 
    * 
    * FIXME
    */
    @Override
    public void shutdown() {
        // this.Listening = !this.Listening; // FIXME
        System.exit(0);

    }
    /**
    * Accepting connections on the port, we are bound to.
    * The main loop of the server is a bit broken. Does not exit,
    * if we flip the value of this.Listening, but exit on the next incoming
    * connection. This is a problem.
    * 
    * FIXME
    */
    @Override
    public void run() {
        try {
            System.out.printf("Listening on %d\n", this.serverSocket.getLocalPort());
            Thread.currentThread().setName("ServerThread");
            // FIXME
            do {
                new Thread(new ServerWorkerThreads(this.serverSocket.accept(), 3)).start();
            } while (this.Listening);

            this.serverSocket.close();
            System.exit(0);
        } catch (IOException ioe) {
            System.err.printf("Cannot accept on, or close port %d\nAdditional information:\n%s\nExiting\n", this.serverSocket.getLocalPort(), ioe.getMessage());
            System.exit(1);
        }
    }
}
.

コメントで言ったように、変数the.listeningの値を否定/フリップ/変更すると、ループは停止しませんが、次の接続で終了します。

列挙子にサーバを実装していませんでした。まず、シリアル化後にシングルトンになることはできませんでしたが、それがそうすることを期待して実行されました。私はしばらく試してみました(条件)、そしてまたそのwhile(条件)ループ。

すべての助けが高くなるでしょう。

役に立ちましたか?

解決

あなたのシャットダウン方法では、変数を設定する代わりにソケットを閉じます:

this.serverSocket.close()
.

これは、acceptループで socketException を上げ、ループは停止します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top