java - 为什么套接字在运行方法中被关闭?

标签 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 已关闭,但在构造函数中已打开。

问题:如何防止socket在run方法中被关闭,以便我可以访问它的输出流?

最佳答案

不要将 try with resources 与 Socket 作为资源一起使用,因为在这种情况下,资源(这里是套接字)将在 try block 退出后立即关闭。

关于java - 为什么套接字在运行方法中被关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38936630/

相关文章:

sockets - socket recv() 是否强制刷新 socket send() 缓冲区?

java - 发送蓝色 : sending mail with attachement to sendinblue

java - 在java中测试同步

java - 如何使用 Java API 根据多个字段对 Elasticsearch 记录进行排序?

java - 任何方式只忽略 "connection reset by peer"IOExceptions

c++ - 基本套接字服务器

java - 使用正则表达式验证电话号码?

java - 时间转换问题

c++ - recvfrom() 是否在出错时修改 src_addr?

node.js - 如何最好地使用socket.io和pub/sub创建与API调用的连接-Node.js