编码多线程套接字代理:IOException SocketClosed 在不应该的地方

Coding a MultiThreaded Socket Proxy: IOException SocketClosed where it shouldn't

我刚开始为 TCP 套接字连接编写代理,虽然我正在检查套接字是否仍然打开,但我收到了 IOException。 这是导致它的 LOC。任何人都知道为什么会发生这种情况?

while (!from.isClosed() && !to.isClosed() && (numOfBytes = in.read(byteBuffer)) != -1) 

我已经调试了代码; from&to勾选时没有关闭。

上下文:

Proxy.java

public class Proxy
{

    public static void main(String[] args)
    {
        try (ServerSocket proxyServer = new ServerSocket(5432))
        {
            int i = 0;
            while (true)
            {
                Socket client = proxyServer.accept();
                System.out.println(i++);
                Socket server = new Socket("localhost", 5000);
                ProxyHandler clientToServer = new ProxyHandler(client, server);
                ProxyHandler serverToClient = new ProxyHandler(server, client);
                clientToServer.setName("client->server"+i);
                serverToClient.setName("server->client"+i);
                clientToServer.start();
                serverToClient.start();
                System.out.println("proxy started");
            }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

ProxyHandler.java

public class ProxyHandler extends Thread
{

    private Socket from;
    private Socket to;

    public ProxyHandler(Socket from, Socket to)
    {
        this.from = from;
        this.to = to;
    }

    @Override
    public void run()
    {
        try (DataInputStream in = new DataInputStream(from.getInputStream());
                DataOutputStream out = new DataOutputStream(to.getOutputStream()))
        {

            byte[] byteBuffer = new byte[1024];
            int numOfBytes = 0;
            while (!from.isClosed() && !to.isClosed() && (numOfBytes = in.read(byteBuffer)) != -1)
            {
                out.write(byteBuffer, 0, numOfBytes);
                out.flush();
                System.out.println(getName() + "(" + numOfBytes + ") ");
                System.out.println(new String(byteBuffer, "UTF-8"));
            }
            System.out.println("left : " + getName());
        }
        catch (IOException io)
        {
            System.out.println("IOException: " + io.getMessage() + " " + getName());
            io.printStackTrace();

        }
    }
}

isClosed() 只有 returns true 如果您自己明确关闭了套接字。它不能用于检测意外断开连接。