Java 如何中断 ServerSocket accept() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2983835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:16:04  来源:igfitidea点击:

How can I interrupt a ServerSocket accept() method?

javanetworkingblockinginterrupt

提问by lukeo05

In my main thread I have a while(listening)loop which calls accept()on my ServerSocket object, then starts a new client thread and adds it to a Collection when a new client is accepted.

在我的主线程中,我有一个while(listening)循环调用accept()我的 ServerSocket 对象,然后启动一个新的客户端线程,并在接受新客户端时将其添加到集合中。

I also have an Admin thread which I want to use to issue commands, like 'exit', which will cause all the client threads to be shut down, shut itself down, and shut down the main thread, by turning listening to false.

我还有一个管理线程,我想用它来发出命令,比如“退出”,这将导致所有客户端线程关闭,关闭自身,并关闭主线程,方法是将侦听设置为 false。

However, the accept()call in the while(listening)loop blocks, and there doesn't seem to be any way to interrupt it, so the while condition cannot be checked again and the program cannot exit!

然而,循环中的accept()调用while(listening)阻塞了,而且似乎没有任何方法可以中断它,因此无法再次检查while条件,程序无法退出!

Is there a better way to do this? Or some way to interrupt the blocking method?

有一个更好的方法吗?或者有什么方法可以中断阻塞方法?

采纳答案by Simon Groenewolt

You can call close()from another thread, and the accept()call will throw a SocketException.

你可以close()从另一个线程调用,accept()调用会抛出一个SocketException.

回答by Lauri Lehtinen

Is calling close()on the ServerSocketan option?

呼唤close()ServerSocket一个选择吗?

http://java.sun.com/j2se/6/docs/api/java/net/ServerSocket.html#close%28%29

http://java.sun.com/j2se/6/docs/api/java/net/ServerSocket.html#close%28%29

Closes this socket. Any thread currently blocked in accept() will throw a SocketException.

关闭此套接字。当前在 accept() 中阻塞的任何线程都将抛出 SocketException。

回答by Juha Syrj?l?

Set timeout on accept(), then the call will timeout the blocking after specified time:

设置 timeout on accept(),则调用将在指定时间后超时阻塞:

http://docs.oracle.com/javase/7/docs/api/java/net/SocketOptions.html#SO_TIMEOUT

http://docs.oracle.com/javase/7/docs/api/java/net/SocketOptions.html#SO_TIMEOUT

Set a timeout on blocking Socketoperations:

ServerSocket.accept();
SocketInputStream.read();
DatagramSocket.receive();

The option must be set prior to entering a blocking operation to take effect. If the timeout expires and the operation would continue to block, java.io.InterruptedIOExceptionis raised. The Socketis not closed in this case.

设置阻塞Socket操作的超时时间:

ServerSocket.accept();
SocketInputStream.read();
DatagramSocket.receive();

该选项必须在进入阻止操作之前设置才能生效。如果超时到期并且操作将继续阻塞,java.io.InterruptedIOException则引发。该Socket不会在这种情况下关闭。

回答by stu

Another thing you can try which is cleaner, is to check a flag in the accept loop, and then when your admin thread wants to kill the thread blocking on the accept, set the flag (make it thread safe) and then make a client socket connection to the listening socket. The accept will stop blocking and return the new socket. You can work out some simple protocol thing telling the listening thread to exit the thread cleanly. And then close the socket on the client side. No exceptions, much cleaner.

您可以尝试的另一件事更干净,是检查接受循环中的标志,然后当您的管理线程想要终止接受阻塞的线程时,设置标志(使其成为线程安全),然后创建客户端套接字连接到侦听套接字。接受将停止阻塞并返回新的套接字。您可以制定一些简单的协议来告诉监听线程干净地退出线程。然后在客户端关闭套接字。没有例外,干净多了。

回答by Soham Malakar

The reason ServerSocket.close()throws an exceptionis because you have an outputstreamor an inputstreamattached to that socket. You can avoid this exception safely by first closing the input and output streams. Then try closing the ServerSocket. Here is an example:

ServerSocket.close()抛出异常的原因 是因为您有一个outputstream或一个inputstream附加到该套接字。您可以通过首先关闭输入和输出流来安全地避免此异常。然后尝试关闭ServerSocket. 下面是一个例子:

void closeServer() throws IOException {
  try {
    if (outputstream != null)
      outputstream.close();
    if (inputstream != null)
      inputstream.close();
  } catch (IOException e1) {
    e1.printStackTrace();
  }
  if (!serversock.isClosed())
    serversock.close();
  }
}

You can call this method to close any socket from anywhere without getting an exception.

您可以调用此方法从任何地方关闭任何套接字而不会出现异常。

回答by Nickolay Savchenko

You can just create "void" socket for break serversocket.accept()

您可以创建“void”套接字来中断 serversocket.accept()

Server side

服务器端

private static final byte END_WAITING = 66;
private static final byte CONNECT_REQUEST = 1;

while (true) {
      Socket clientSock = serverSocket.accept();
      int code = clientSock.getInputStream().read();
      if (code == END_WAITING
           /*&& clientSock.getInetAddress().getHostAddress().equals(myIp)*/) {
             // End waiting clients code detected
             break;
       } else if (code == CONNECT_REQUEST) { // other action
           // ...
       }
  }

Method for break server cycle

中断服务器周期的方法

void acceptClients() {
     try {
          Socket s = new Socket(myIp, PORT);
          s.getOutputStream().write(END_WAITING);
          s.getOutputStream().flush();
          s.close();
     } catch (IOException e) {
     }
}

回答by Michael Sims

OK, I got this working in a way that addresses the OP's question more directly.

好的,我以一种更直接地解决 OP 问题的方式进行了这项工作。

Keep reading past the short answer for a Thread example of how I use this.

继续阅读我如何使用它的 Thread 示例的简短答案。

Short answer:

简短的回答:

ServerSocket myServer;
Socket clientSocket;

  try {    
      myServer = new ServerSocket(port)
      myServer.setSoTimeout(2000); 
      //YOU MUST DO THIS ANYTIME TO ASSIGN new ServerSocket() to myServer?!
      clientSocket = myServer.accept();
      //In this case, after 2 seconds the below interruption will be thrown
  }

  catch (java.io.InterruptedIOException e) {
      /*  This is where you handle the timeout. THIS WILL NOT stop
      the running of your code unless you issue a break; so you
      can do whatever you need to do here to handle whatever you
      want to happen when the timeout occurs.
      */
}

Real world example:

现实世界的例子:

In this example, I have a ServerSocket waiting for a connection inside a Thread. When I close the app, I want to shut down the thread (more specifically, the socket) in a clean manner before I let the app close, so I use the .setSoTimeout() on the ServerSocket then I use the interrupt that is thrown after the timeout to check and see if the parent is trying to shut down the thread. If so, then I set close the socket, then set a flag indicating that the thread is done, then I break out of the Threads loop which returns a null.

在这个例子中,我有一个 ServerSocket 在一个线程内等待连接。当我关闭应用程序时,我想在关闭应用程序之前以干净的方式关闭线程(更具体地说,套接字),所以我在 ServerSocket 上使用 .setSoTimeout() 然后我使用抛出的中断超时后检查并查看父级是否试图关闭线程。如果是这样,那么我设置关闭套接字,然后设置一个指示线程已完成的标志,然后我退出返回空值的线程循环。

package MyServer;

import javafx.concurrent.Task;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import javafx.concurrent.Task;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class Server {

public Server (int port) {this.port = port;}

private boolean      threadDone        = false;
private boolean      threadInterrupted = false;
private boolean      threadRunning     = false;
private ServerSocket myServer          = null;
private Socket       clientSocket      = null;
private Thread       serverThread      = null;;
private int          port;
private static final int SO_TIMEOUT    = 5000; //5 seconds

public void startServer() {
    if (!threadRunning) {
        serverThread = new Thread(thisServerTask);
        serverThread.setDaemon(true);
        serverThread.start();
    }
}

public void stopServer() {
    if (threadRunning) {
        threadInterrupted = true;
        while (!threadDone) {
            //We are just waiting for the timeout to exception happen
        }
        if (threadDone) {threadRunning = false;}
    }
}

public boolean isRunning() {return threadRunning;}


private Task<Void> thisServerTask = new Task <Void>() {
    @Override public Void call() throws InterruptedException {

        threadRunning = true;
        try {
            myServer = new ServerSocket(port);
            myServer.setSoTimeout(SO_TIMEOUT);
            clientSocket = new Socket();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while(true) {
            try {
                clientSocket = myServer.accept();
            }
            catch (java.io.InterruptedIOException e) {
                if (threadInterrupted) {
                    try { clientSocket.close(); } //This is the clean exit I'm after.
                    catch (IOException e1) { e1.printStackTrace(); }
                    threadDone = true;
                    break;
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
};

}

Then, in my Controller class ... (I will only show relevant code, massage it into your own code as needed)

然后,在我的Controller类中......(我只会展示相关代码,根据需要将其按摩到您自己的代码中)

public class Controller {

    Server server = null;
    private static final int port = 10000;

    private void stopTheServer() {
        server.stopServer();
        while (server.isRunning() {
        //We just wait for the server service to stop.
        }
    }

    @FXML private void initialize() {
        Platform.runLater(()-> {
            server = new Server(port);
            server.startServer();
            Stage stage = (Stage) serverStatusLabel.getScene().getWindow();
            stage.setOnCloseRequest(event->stopTheServer());
        });
    }

}

I hope this helps someone down the road.

我希望这可以帮助某人在路上。