【问题标题】:Java threading, shutting down a server thread from a main JFrame GUIJava 线程,从主 JFrame GUI 关闭服务器线程
【发布时间】:2014-03-29 18:33:20
【问题描述】:

我有一个程序可以启动一个被动服务器,它为每个到服务器套接字的连接生成一个连接处理程序。我想找到一种雄辩的方法来关闭服务器套接字并释放端口。目前,我不确定如何中断Socket.accept 方法。我一直在使用同步方法在另一个线程中设置标志,但 Socket.accpet 阻塞直到建立连接。

我的被动服务器代码

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

 }

【问题讨论】:

    标签: java multithreading swing sockets


    【解决方案1】:

    如果您不想通过关闭侦听套接字来强制异常(这是非常好的 IME),则设置一个 volatile boolean 'shutdown' 标志,在每次 accept() 返回后检查该标志。然后通过打开 localhost 客户端连接使 accept() 调用返回。

    【讨论】:

      【解决方案2】:

      您可以在服务器/后台线程上调用interruptclose
      在服务器套接字上。我不知道后者,只是谷歌了它。

      另见:

      How to terminate a thread blocking on socket IO operation instantly?

      【讨论】:

        【解决方案3】:

        您可以在 ServerSocket 上调用 close()。挂起的接受调用会抛出一个 SocketException,因此您可以捕获它以获得干净的退出。

        【讨论】:

          猜你喜欢
          • 2013-02-27
          • 2015-02-05
          • 2017-11-09
          • 1970-01-01
          • 2010-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-02
          相关资源
          最近更新 更多