服务器:
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
已关闭,但在构造函数中已打开。
问题:如何防止socket在run方法中被关闭,以便我可以访问它的输出流?
最佳答案
不要将 try with resources 与 Socket 作为资源一起使用,因为在这种情况下,资源(这里是套接字)将在 try block 退出后立即关闭。
关于java - 为什么套接字在运行方法中被关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936630/