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

时间:2012-10-03 19:58:09

标签: java multithreading serversocket

我有一个程序我正在处理主线程初始化一个侦听器线程以侦听到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实现的主要功能是“停止”,它应检查没有连接,然后停止监听器及其自身。

这是监听器线程:

   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()调用。

想法?

1 个答案:

答案 0 :(得分:2)

使用布尔标志来表示它是否应该中断:

private volatile boolean stop = false;

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

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

然后,几乎在这里,在catch块中接受你的ServerSocket进入Socket的代码行中,就像这样:

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();
        }
    }