gpt4 book ai didi

java - 为什么当我退出程序时它警告我套接字已关闭?

转载 作者:行者123 更新时间:2023-12-02 00:27:42 24 4
gpt4 key购买 nike

这是我的程序,它有两个线程,一个是监听用户输入,另一个是套接字:

        bio = new BasicConsoleIO();
bio.assignObject(worker);

Thread b = new Thread(bio);
b.start();

Thread a = new Thread(worker);
a.start();

worker是一个socket,BasicConsoleIO负责监听用户输入BasicConsoleIO 是这样的:

private Worker worker;
static BufferedReader reader;

@Override
public void run() {
//......Code Skip......//
if (inputString.equalsIgnoreCase("q")) {
this.applicationQuit();
}
}

public void applicationQuit(){
this.getWorker().stopWorking();
System.exit(0);
}

当按下'q'时,应用程序将调用Worker关闭套接字,并退出程序,Worker的工作方式如下:

private ServerSocket providerSocket;
private Socket socket = null;

int port = 1234;

Worker() {
}

public void stopWorking() {
System.out.println("worker stop working");

try {
if (providerSocket != null) {
providerSocket.close();
}
if (socket != null) {
socket.close();
}

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

@Override
public void run() {

try {
providerSocket = new ServerSocket(this.port);

while (true) {
if (!providerSocket.isClosed()) {

socket = providerSocket.accept();

WorkTask wt = new WorkTask();
wt.setSocket(socket);

Thread a = new Thread(wt);
a.start();
}
}

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

worker会持续监听请求,并在单独的线程中分配新的工作任务,工作任务的详细信息如下:

Socket socket;
ObjectOutputStream out;
ObjectInputStream in;
Object receivedObj;
String message;

@Override
public void run() {
try {

do {
out.flush();
receivedObj = in.readObject();

//......Code Skip......//

} while (receivedObj != null
&& !receivedObj.equals(SharedConstant.SOCKET_EOF_STRING));

if (in != null) {
in.close();
}
if (out != null) {
out.close();
}

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

但是当我启动该程序并按“q”退出时,它会警告我以下错误:

Please assign a port number 2333 Press 'q' to kill to programme Waiting for connection: 2333 q worker stop working Run me anyway! java.net.SocketException: Socket closed at java.net.PlainSocketImpl.socketAccept(Native Method) at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:408) at java.net.ServerSocket.implAccept(ServerSocket.java:462) at java.net.ServerSocket.accept(ServerSocket.java:430) at com.mydefault.package.Worker.run(Worker.java:61) at java.lang.Thread.run(Thread.java:680)

最佳答案

你可以看到

socket = providerSocket.accept();

抛出异常,因为在

public void stopWorking() {
// Socket won't close unless the user make it to close
// 4: Closing connection
System.out.println("worker stop working");

try {
if (providerSocket != null) {
providerSocket.close();

你关闭了它。

如果您想避免此错误,我有一个 volatile boolean 闭合字段,我将其设置为true并在报告错误之前进行检查。即当我关闭时忽略错误。

关于java - 为什么当我退出程序时它警告我套接字已关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682003/

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