编写MultiThreaded套接字代理:IOException SocketClosed它不应该在哪里

时间:2015-03-16 21:17:25

标签: java multithreading sockets proxy

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

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

我已经调试了代码;来自&在检查时不会关闭。

for context:

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();

        }
    }
}

1 个答案:

答案 0 :(得分:3)

如果您自己已明确关闭套接字,则

isClosed()仅返回true。它不能用于检测意外断开连接。