gpt4 book ai didi

java - 在Java中干净地停止监听serversocket的线程

转载 作者:行者123 更新时间:2023-12-02 07:32:40 24 4
gpt4 key购买 nike

我正在开发一个程序,其中主线程初始化一个监听器线程来监听到 serverSocket 的传入连接

    /*
* run - this will set up the server so that it is ready to listen.
*/
public void run( serverVariables servVar, storageManager writer, storageVariables write, CoreVariables coreVar, serverFunctions serv, SQLFunctions SQL, SQLvariables SQLvar, netFunctions conn, netVariables netVar) {
ControlFunctions cntrl = new ControlFunctions();
util.doCommand("ifconfig eth0 " + servVar.ip);
ListenerThread listen = new ListenerThread(servVar, coreVar, writer, serv, write, SQL, SQLvar, util);
try {
servVar.servSocket = new ServerSocket(servVar.port);
listen.start();
cntrl.getInput(util, clr.YELLOW, SQL, SQLvar, listen, conn, netVar);
} catch (IOException e) {
System.out.println("Could not read input stream");
e.printStackTrace();
}
}

然后等待服务器管理员的输入(在 cntrl.getInput() 中)。这一切都很好,但我试图从 getInput 实现的主要功能是“halt”,它应该检查是否没有连接,然后停止监听器及其本身。

这是监听器线程:

   package server;

import java.io.IOException;

import net.netFunctions;
import net.netVariables;
import core.CoreVariables;
import utl.utilFunctions;
import utl.color;
import server.serverVariables;
import store.storageManager;
import store.storageVariables;
import conn.SQLFunctions;
import conn.SQLvariables;

public class ListenerThread extends Thread {
color clr = new color();
CoreVariables coreVar = new CoreVariables();
utilFunctions util = new utilFunctions();
netVariables netVar = new netVariables();
storageManager writer = new storageManager();
netFunctions conn = new netFunctions();
storageVariables write = new storageVariables();
serverFunctions serv = new serverFunctions();
serverVariables servVar = new serverVariables();
SQLFunctions SQL = new SQLFunctions();
SQLvariables SQLvar = new SQLvariables();
message msg = new message();

public ListenerThread(serverVariables servVar, CoreVariables coreVar,
storageManager writer, serverFunctions serv,
storageVariables write, SQLFunctions SQL, SQLvariables SQLvar,
utilFunctions util) {
super("ListenerThread");
this.coreVar = coreVar;
this.util = util;
this.writer = writer;
this.write = write;
this.serv = serv;
this.servVar = servVar;
this.SQL = SQL;
this.SQLvar = SQLvar;
}

public void run() {
util.outColored("Listener thread started", clr.CYAN);
while (true) {
try {
new ConnectionThread(clr.GREEN, servVar.servSocket.accept(),
coreVar, util, writer, write, serv, servVar, SQL,
SQLvar).start();
} catch (IOException e) {
System.out.println("Failed to accept");
}
}
}
}

和haltServer函数:

private boolean haltServer(SQLFunctions SQL, SQLvariables SQLvar, utilFunctions util, String color, ListenerThread listen, netFunctions conn, netVariables netVar) {
Socket s = null;
boolean success = false;
String result = null;
int count = 0;
//check for open connections
SQL.doQuery("SELECT * FROM Clients WHERE Status != 0", SQLvar);
try {
while(SQLvar.resultSet.next()) {
result = SQLvar.resultSet.getString("ClientID");
util.outColored("Client " + result + " is still connected", color);
count++;
}
if(count == 0) {
listen.stop();
success = true;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return success;
}

我知道 stop 已被贬值,并考虑使用 interupted() 作为标志,但我认为由于 serverSocket.accept() 调用,这不会起作用。

想法?

最佳答案

使用 boolean 标志来表示是否应该中断:

private volatile boolean stop = false;

然后创建一个名为kill(无法停止)的方法,将标志设置为true,然后关闭您的ServerSocket:

public voic kill() {
stop = true;
serverSocket.close();
}

然后,这里几乎完成了,在将 ServerSocket 接受到 Socket 的代码行中,在 catch block 中,如下所示:

try {
//accept server socket
} catch(IOException e) {
if(stop)
return;
e.printStackTrace();
}

因此,当您关闭 ServerSocket 时,它不会打印错误,而只是停止尝试接受连接。最后一件事,将 while 循环更改为:

while(!stop) { ...

只是为了确保它正确退出。

实际上,我的计算机上有一个运行 Java 的服务器,它使用以下代码:

    threadHandler = new ThreadPoolExecutor( maxThreads, maxThreads, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<Runnable>( maxThreads, true ) );
while (!serverTerminated) {
try {
final Socket connectionSocket = serversocket.accept();
SocketHandler handler = new SocketHandler( this, connectionSocket );
threadHandler.submit( handler );
} catch (IOException e) {
if (!serverTerminated)
e.printStackTrace();
}
}

关于java - 在Java中干净地停止监听serversocket的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com