Java循环退出条件

标签 java networking singleton enumerator

我正在用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);
        }
    }
}

现在,正如评论中所述,如果我否定/翻转/更改变量 this.Listening 的值,循环不会停止,而是在下一个连接时退出。

我一开始并没有在枚举器中实现服务器,而是用一个类来实现的,该类在序列化后未能成为单例,但它按照我的预期执行。我尝试了 while(条件)done,以及 do while(条件)循环。

所有帮助将不胜感激。

最佳答案

在您的关闭方法中,只需关闭套接字而不是设置变量:

this.serverSocket.close()

这将在接受循环上引发SocketException,并且循环将停止。

关于Java循环退出条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9665776/

相关文章:

ios - 更好的是,委托(delegate)或单例在 View Controller 之间传递数据 - Objective-C

java - 序列化 java.util.Enumeration

java - java或c中的按位运算

java - 如何在android中解析JSON字符串数组

java - 使用 Graphics2D 翻转图像

c# - 网络套接字-仅第一条消息总是会完成

python - PySocks代理功能可以与praw API一起使用吗?

linux - pptp vpn 同时连接和互联网 (fedora12)

java - 我可以创建一个作为泛型类型参数的成员变量吗?

java - 使用 Singleton 与扩展 Application 类