4

我有一个在服务器(服务器 A)上运行的程序,它在一个端口上侦听外部连接(来自外部服务器,B),然后在另一个端口上侦听同一服务器(服务器 A)上的内部连接。然后它将数据从内部连接传递到外部连接并再次返回。

我想知道是否有一种方法可以检测到外部客户端已断开连接。我一次只需要一个外部连接,但如果外部客户端重新启动或类似情况,我希望能够接受一个新连接。

这个套接字级别的东西对我来说都是相当新的,所以如果有更好的方法来解决这个问题,我会全神贯注。一个规定是服务器 B 上运行的客户端必须是发起连接的客户端,并且连接必须尽可能长。

public void handleConnection() {
    System.out.println("Waiting for client message...");
    try {
        SSLSocket extSocket = (SSLSocket) this.externalServerSocket.accept();

        ObjectInputStream externalOis = new ObjectInputStream(extSocket.getInputStream());
        ObjectOutputStream externalOos = new ObjectOutputStream(extSocket.getOutputStream());
        System.out.println("Client connection establisthed");
        // Loop here to accept all internal connections
        while (true) {

            SSLSocket internalSocket = (SSLSocket) this.internalServerSocket.accept();
            new ConnectionHandler(externalOis, externalOos, internalSocket);

        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        return;
    }
}

class ConnectionHandler implements Runnable {
    private SSLSocket internalSocket;

    private ObjectOutputStream internalOos;
    private ObjectInputStream internalOis;

    private ObjectInputStream externalOis;
    private ObjectOutputStream externalOos;

    public ConnectionHandler(ObjectInputStream externalOis,
            ObjectOutputStream externalOos, SSLSocket internalSocket) {

        this.internalSocket = internalSocket;

        try {
            this.internalOis = new ObjectInputStream(this.internalSocket.getInputStream());
            this.internalOos = new ObjectOutputStream(this.internalSocket.getOutputStream());

            this.externalOis = externalOis;
            this.externalOos = externalOos;

        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
        new Thread(this).start();
    }

    @Override
    public void run() {
        try
        {

          // process data
          Object o = internalOis.readObject();
            externalOos.writeObject(o);
            Object o2 = externalOis.readObject();
            internalOos.writeObject(02);

            internalOos.close();
            internalOis.close();

            this.internalSocket.close();

        } catch (IOException e) {
            System.err.println(e.getMessage());
        } catch (ClassNotFoundException e) {
            System.err.println(e.getMessage());
        }
    }
}
4

1 回答 1

0

如果客户端断开连接,readObject()将抛出EOFExceptionwrite()并将抛出IOException: connection reset. 这就是你所需要的。

于 2017-02-22T04:49:55.073 回答