简体   繁体   English

如何在不使用while循环的情况下运行服务器?

[英]How to run a Server without using a while loop?

I'm trying to make a server program using the DatagramSocket and DatagramPacket classes, but my current code uses an ugly while loop which also freezes my program while the server runs, but the server runs fine with no problems. 我正在尝试使用DatagramSocket和DatagramPacket类创建一个服务器程序,但是我当前的代码使用了一个丑陋的while循环,它在服务器运行时也冻结了我的程序,但服务器运行良好而没有任何问题。 Anyway the code is below. 无论如何,代码如下。 Is there anyway I can use something different than a while loop or prevent the while loop from preventing any other code in the program to execute? 无论如何我可以使用不同于while循环的东西或阻止while循环阻止程序中的任何其他代码执行?

protected void run() {
    try {
        socket = new DatagramSocket(port);
        socket.setBroadcast(true);
    } catch (Exception e) {
        e.printStackTrace();
        stopServer(); //stop the server
        return; 
    }
    while(isRunning()){ //hate this loop
        try {
            byte[] buf = new byte[256];
            DatagramPacket packet = new DatagramPacket(buf, 256);
            socket.receive(packet);
            DatagramPacket serverPacket;
            byte[] serverBuf;
            byte hb = 0;
            byte lb = packet.getData()[0];
            int e = ((int)hb<<8)|((int)lb&0xFF); //translate byte to int
            switch(e) {
                case 2:
                    //do something
                    break;
                case 5:
                   //do something
                   break;
                case 7:
                    //do something
                    break;
                default:
                    //default stuff
                    break;
            }
        } catch (Exception e) {
            System.out.println("Fatal Server Error:");
            e.printStackTrace(); 
            stopServer(); //stop the server
            return; //stop the method
        }
    }
}

You should put this in a new thread. 你应该把它放在一个新的线程中。 The process of receiving a packet involves synchronous IO, so it will always block whichever thread it's running in. 接收数据包的过程涉及同步IO,因此它将始终阻止它运行的任何线程。

To clarify, it's not the while loop itself that makes the rest of the program wait. 为了澄清,它不是while循环本身使程序的其余部分等待。 It's the socket.receive() call. 这是socket.receive()调用。

I doubt that you can get rid of the loop because you, logically, intend that your server "serves" multiple requests. 我怀疑你可以摆脱循环,因为从逻辑上讲,你打算让你的服务器“服务”多个请求。 Every request will be served in one iteration from the server loop. 每个请求将在服务器循环的一次迭代中提供。

Now, it is customary that your server will only care about receiving the requests and will dispatch them to a thread pool to be processed. 现在,习惯上您的服务器只关心接收请求并将它们分派给要处理的线程池。

As such, you do not make your server thread worry about the processing of a given request. 因此,您不会让服务器线程担心给定请求的处理。 Basically because if your server is busy processing the request it cannot attend any other ones arriving to its port during that time. 基本上是因为如果您的服务器忙于处理请求,那么在此期间它无法访问到达其端口的任何其他服务器。

The recommendation would be, receive the packets, and immediatelly pass the received data to another thread for processing. 建议是,接收数据包,并立即将接收到的数据传递给另一个线程进行处理。

This, evidently, will not imply the removal of the loop in question, which as I mentioned, is not possible unless you intend to serve only one request from your clients (a rather unlikely scenario). 显然,这并不意味着删除有问题的循环,正如我所提到的,除非您打算只提供来自客户的一个请求(这是一个相当不可能的场景),否则这是不可能的。 This would guarantee that the requests can be proccessed independently and their processing will not delay attending other requests arriving at the server port. 这将保证请求可以独立进行,并且它们的处理不会延迟参与到达服务器端口的其他请求。

I would recommend using Apache Mina to manage your flow and network communication. 我建议使用Apache Mina来管理您的流量和网络通信。

It was designed for this particularly and provides an implementation of the Reactor design pattern which might be a better design choice for your application. 它专为此而设计,并提供了Reactor设计模式的实现,这可能是您的应用程序的更好的设计选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用while()循环在vertx上运行无限循环 - How to run infinite loop on vertx using while() loop 如何使用for循环运行数组并执行while循环 - how to run array using for loop and do while loop 如何在不使用 tomcat 的情况下运行 jersey-server webservice 服务器 - How to run jersey-server webservice server without using tomcat 如何在while循环中运行扫描仪 - How to run scanner in a while loop 如何使方法从头开始运行而不使用循环 - How to make the method run from the beginning Without using a Loop 在不使用 If 或 Break 的情况下中断 while 循环 - Break a while loop without using If or Break 在调用方法时,如何在循环内使用扫描仪输入的变量使用哨兵值时运行此 while 循环? - How can I get this while loop to run when using a sentinel value for a variable with scanner input inside of the loop, while calling methods? 如何多次运行while循环 - how to run a while loop several time 如何在不冻结我的应用程序的情况下运行循环? - How to run loop without freezing my app? 为什么这个&#39;if&#39;语句不会在while循环中运行而没有其他东西也会在while循环中运行? - Why won't this 'if' statement run in a while loop without something else also happening in the while loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM