简体   繁体   English

Java线程,从主JFrame GUI关闭服务器线程

[英]Java threading, shutting down a server thread from a main JFrame GUI

I have a program that starts up a passive server that spawns a connection handler for each connection to the server socket. 我有一个程序可以启动一个被动服务器,该服务器为与服务器套接字的每个连接生成一个连接处理程序。 I would like to find an eloquent way to shutdown the server socket and release the port. 我想找到一种雄辩的方法来关闭服务器套接字并释放端口。 Currently, I am not sure how to interrupt the Socket.accept method. 当前,我不确定如何中断Socket.accept方法。 I have been using a synchronized method to set a flag in another Thread, but Socket.accpet blocks until a connection is made. 我一直在使用同步方法在另一个线程中设置标志,但是Socket.accpet阻塞,直到建立连接为止。

My passive server code 我的被​​动服务器代码

package NetSecConsole;

import java.io.*;
import java.net.*;
import javax.swing.SwingUtilities;


public class PassiveServer implements Runnable
{
    Thread runner;
    int port = 20000;
    MainFrame mainFrame;
    ServerSocket s = null;

    public PassiveServer(MainFrame mf, int hostPort) 
    {
        mainFrame = mf;
        port = hostPort;
        try 
        {
            s = new ServerSocket(hostPort);
        } 
        catch (Exception e) 
        {
            newStatus("Server [Constructor]: Could not open server socket! " + e);
        }
    }

    public void start() 
    {
        if (runner == null) 
        {
            runner = new Thread(this);
            runner.start();
        } 
    }

    @Override
    public void run() 
    {
        try 
        {
            int connCount = 1;
            for (;;) 
            {
                // Sit and wait for a connection
                newStatus("Server [run]: Waiting for connection to port " + Integer.toString(port) + "...");
                Socket incomingConnection =  s.accept();

                // Pass the connection off to a connection handler thread
                newStatus("Server [run]: Got connection on port " + Integer.toString(port));
                final ConnectionHandler conHand = new ConnectionHandler(mainFrame, incomingConnection, connCount); 

                // Start the connection handler, then continue;
                conHand.start();
                connCount++;
            } 
        } 
        catch (IOException e) 
        {
            newStatus("Server [run]: IOException: "  + e);
        }
    }

    public final void newStatus(final String arg)
    {
        Runnable sendMsg = new Runnable() 
        {
            @Override
            public void run() 
            {
                    mainFrame.newStatusLine(arg);
            }
        };
        SwingUtilities.invokeLater(sendMsg);
    }

 }

If you don't want to force an exception by closing the listening socket, (which is perfectly fine IME), then set a volatile boolean 'shutdown' flag that that is checked after every accept() return. 如果您不想通过关闭监听套接字(这是很好的IME)来强制执行异常,则设置一个易失的布尔值'shutdown'标志,该标志在每次accept()返回之后都会进行检查。 Then make the accept() call return by opening a localhost client connection. 然后,通过打开localhost客户端连接,使accept()调用返回。

You can call interrupt on the server/background thread or close 您可以在服务器/后台线程上调用interruptclose
on the server socket. 在服务器套接字上。 I didn't know about the latter, just Googled it. 我不知道后者,只是用谷歌搜索。

See also: 也可以看看:

How to terminate a thread blocking on socket IO operation instantly? 如何立即终止套接字IO操作上的线程阻塞?

You can call close() on the ServerSocket. 您可以在ServerSocket上调用close()。 The pending accept call(s) with throw a SocketException, so you can trap that for a clean exit. 待处理的接受调用将引发SocketException,因此您可以将其捕获以进行干净退出。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM