【问题标题】:Coding a MultiThreaded Socket Proxy: IOException SocketClosed where it shouldn't编写多线程套接字代理:IOException SocketClosed 在不应该的地方
【发布时间】:2015-03-16 21:17:24
【问题描述】:

我刚开始编写 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();

        }
    }
}

【问题讨论】:

    标签: java multithreading sockets proxy


    【解决方案1】:

    isClosed() 仅在您自己明确关闭套接字时才返回 true。它不能用于检测意外断开连接。

    【讨论】:

    • 啊谢谢,这对我来说是新的。是否有可靠的方法来确定套接字是否被“另一方”关闭?我唯一的想法是过滤抛出的异常。
    • @elnin0 如果对等端关闭连接,您将从读取中获得流的结束,这取决于您调用的读取方法采取各种形式。这一切都记录在案。在您的情况下,numOfBytes 将是-1:您已经在测试它。如果你正在写作,你最终会得到一个IOException: connection reset'.
    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2013-11-11
    • 1970-01-01
    相关资源
    最近更新 更多