gpt4 book ai didi

Java 服务器套接字中断如何

转载 作者:行者123 更新时间:2023-12-01 23:36:47 24 4
gpt4 key购买 nike

如何停止正在监听客户端的服务器套接字。我的代码如下所示

 private ServerSocket serverSocket;

class ServerThread implements Runnable {

private BufferedReader input;
public void run() {
Socket socket = null;

try {
serverSocket = new ServerSocket(SERVE_LISTEN_RPORT);
} catch (IOException e) {
e.printStackTrace();
}

while (!Thread.currentThread().isInterrupted()) {

try {

socket = serverSocket.accept();
try {

this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

} catch (IOException e) {
e.printStackTrace();
}

try {
String read = input.readLine();
//Do something
}

} catch (IOException e) {
e.printStackTrace();
}

} catch (IOException e) {
e.printStackTrace();
}
}


try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

当我从另一个线程收到命令时,我需要停止这个线程。我已经播种了this有问题但不知道如何实现。

最佳答案

以下是如何从其他线程关闭套接字的示例:

private static volatile ServerSocket serverSocket;

public static void main(String[] args) throws InterruptedException, IOException {
Thread serverThread = new Thread(new ServerThread());
serverThread.start();
Thread.sleep(1000); // wait a bit, then close
serverSocket.close();
}

static class ServerThread implements Runnable {

private BufferedReader input;

public void run() {
try {
serverSocket = new ServerSocket(25);
while (true) {
Socket socket = serverSocket.accept();
// client request handling logic
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

关于Java 服务器套接字中断如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18546905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com