英文:
How do I close a multithreaded server?
问题
以下是您提供的代码的中文翻译部分:
public class TaskListServer {
public static List<String> taskList = new ArrayList<>();
public static String uniqueString(){
return String.join(", ", taskList);
}
public static void addTasks(String task) {
taskList.add(task);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
ServerSocket serverSocket = new ServerSocket(4242);
while (true) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
}catch (IOException e) {
e.printStackTrace();
}
sc.close();
}
}
英文:
So I have a program that clients can enter any type of tasks and other clients can check it as well but I don't know how to close the loop that tries to accept new connetions to the server.
What I want is when I close the last client running using a command I wrote I want the server to close as well.
Can anyone help?
public class TaskListServer {
public static List<String> taskList = new ArrayList<>();
public static String uniqueString(){
return String.join(", ", taskList);
}
public static void addTasks(String task) {
taskList.add(task);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
ServerSocket serverSocket = new ServerSocket(4242);
while (true) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
}catch (IOException e) {
e.printStackTrace();
}
sc.close();
}
答案1
得分: 0
不要使用无限循环(while(true)
)。
private static boolean acceptNewClients = true;
public static void flipAcceptNewClients() {
acceptNewClients = !acceptNewClients;
}
public static void main(String[] args) {
/* 你的代码在这里 */
while (acceptNewClients) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
/* 你的代码在这里 */
}
英文:
Don't use an infinity loop (while(true)
).
private static boolean acceptNewClients = true;
public static void flipAcceptNewClients() {
acceptNewClients = !acceptNewClients;
}
public static void main(String[] args) {
/* your code here */
while (acceptNewClients) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
/* your code here */
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论