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

时间:2016-08-13 20:17:22

标签: 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());
    }
}
}

客户端:

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

输出:

Constructor: is socket closed? false
Run method: is socket closed? true

从输出中可以看出,当调用run方法时,socket被关闭,但在构造函数中它被打开了。

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

0 个答案:

没有答案