簡體   English   中英

我如何才能避免此Java服務器中的無限循環?

[英]How can I possibly avoid infinite loop in this java server?

我不是在談論線程或任何使事情變得更復雜的事情。 我看到的大多數服務器程序都是這樣或while(true){...}(相同的概念)。

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.DataOutputStream;
import java.io.IOException;

public class TCPServer {
    ServerSocket welcomeSocket;
    public TCPServer(int port) throws IOException {
        welcomeSocket = new ServerSocket(port);
    }

    public void go() throws IOException {
        // This is not a valid way to wait for a socket connection, You should
        // not have a forever loop or while(true) 
        **for (; ;) {**
            Socket connectionSocket = welcomeSocket.accept();
            Scanner clientIn = new Scanner(connectionSocket.getInputStream());
            DataOutputStream clientOut = new DataOutputStream(connectionSocket.getOutputStream());
            String clientLine = clientIn.nextLine();
            String modLine = clientLine.toUpperCase();
            clientOut.writeBytes(modLine + "\n");
        }
    }

    public static void main(String[] args){
        try {
            TCPServer server = new TCPServer(6789);
            server.go();
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

它不是永久循環的,您的代碼在welcomeSocket.accept()行上welcomeSocket.accept()直到有人連接為止;只有在執行下一行之后,它才會在welcomeSocket.accept()上等待新的連接。 換句話說,它會根據需要(每個連接)循環多次。 如果只想只允許一個客戶端連接,請刪除for (; ;)語句。 但是,這將需要每次重新啟動服務器。

您可以在池中具有任意數量的線程的情況下運行調度程序,並防止主線程終止。 在這里,我使用了輸入流,但是您可以用不同的方式來做。 在這里,您可以使用多個線程來獲得連接並自定義調度程序的頻率。

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class MyTest {

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);

@Test
public void hello() {
    final Runnable helloServer = new Runnable() {
        public void run() {
            // handle soket connection here
            System.out.println("hadling connection");
        }
    };
    final ScheduledFuture<?> helloHandle = scheduler.scheduleAtFixedRate(helloServer, 1000, 1000, TimeUnit.MILLISECONDS);

    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

while(!finished)選項可能比“空” for循環更好。 發生退出事件時,只需將finish設置為true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM