简体   繁体   English

如何中断 ServerSocket accept() 方法?

[英]How can I interrupt a ServerSocket accept() method?

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)循环,它在我的ServerSocket对象上调用accept() ,然后启动一个新的客户端线程,并在接受新客户端时将其添加到集合中。

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.我还有一个管理线程,我想用它来发出命令,例如'exit' ,这将导致所有客户端线程关闭,关闭自身,并关闭主线程,方法是将侦听设置为 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!但是, while(listening)循环中的accept()调用阻塞了,而且似乎没有任何方法可以中断它,因此无法再次检查while 条件,程序无法退出!

Is there a better way to do this?有一个更好的方法吗? Or some way to interrupt the blocking method?或者有什么方法可以中断阻塞方法?

您可以从另一个线程调用close() ,并且accept()调用将抛出SocketException

Set timeout on accept() , then the call will timeout the blocking after specified time: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 Socket operations:设置阻塞Socket操作的超时时间:

 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.InterruptedIOException is raised.如果超时到期并且操作将继续阻塞,则会引发java.io.InterruptedIOException The Socket is not closed in this case.在这种情况下, Socket没有关闭。

Is calling close() on the ServerSocket an option?ServerSocket上调用close()是一种选择吗?

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。

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

The reason ServerSocket.close() throws an exception is because you have an outputstream or an inputstream attached to that socket. ServerSocket.close()抛出异常的原因是因为您有一个outputstream或一个输入inputstream附加到该套接字。 You can avoid this exception safely by first closing the input and output streams.您可以通过首先关闭输入和输出流来安全地避免此异常。 Then try closing the ServerSocket .然后尝试关闭ServerSocket Here is an example:下面是一个例子:

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.您可以调用此方法从任何地方关闭任何套接字而不会出现异常。

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

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.我希望这可以帮助某人在路上。

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.没有例外,干净多了。

You can simply pass the timeout limit (milli seconds) as a parameter while calling accept function.您可以在调用接受函数时简单地将超时限制(毫秒)作为参数传递。

eg serverSocket.accept(1000);例如 serverSocket.accept(1000); automatically close the request after 1 sec 1秒后自动关闭请求

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

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