为什么在run方法中关闭套接字?

Den*_*nch 1 java sockets

服务器:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public final class Server {

public static void main(String[] args) {
    new Server().start();
}

public void start() {

    ExecutorService executorService = Executors.newFixedThreadPool(10);
    try (ServerSocket serverSocket = new ServerSocket(1200)) {
        while (true) {
            try (Socket socket = serverSocket.accept()) {
                executorService.submit(new SocketHandler(socket));
            } catch (IOException e) {
                System.out.println("Error accepting connections");
            }
        }
    } catch (IOException e) {
        System.out.println("Error starting server");
    }
}

public final class SocketHandler implements Runnable {

    private final Socket socket;

    public SocketHandler(Socket connection) {
        this.socket = connection;
        System.out.println("Constructor: is socket closed? " + this.socket.isClosed());
    }

    @Override
    public void run() {
        System.out.println("Run method: is socket closed? " + this.socket.isClosed());
    }
}
}
Run Code Online (Sandbox Code Playgroud)

客户:

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

public final class Client{

public static void main(String[] args) {

    try (Socket socket = new Socket("localhost", 1200)) {
    } catch (IOException e) {}
}
Run Code Online (Sandbox Code Playgroud)

输出:

Constructor: is socket closed? false
Run method: is socket closed? true
Run Code Online (Sandbox Code Playgroud)

正如您在输出中看到的那样,当调用run方法时socket,它被关闭,但是在构造函数中它被打开了.

问题:如何防止套接字在run方法中关闭,以便我可以访问其输出流?

Hov*_*els 5

不要使用带有Socket资源的try作为资源,因为在这种情况下,因为资源(这里是套接字)将在try块退出后立即关闭.