如何检测客户端何时与服务器断开连接

时间:2012-10-03 14:43:06

标签: java sockets

我有一个在服务器(服务器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());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果客户端断开连接,<table> <tr> <td>cell</td> <td>cell</td> <td>cell</td> <td>cell</td> <td>cell</td> </tr> </table>将抛出readObject()EOFException将抛出write()。这就是你所需要的一切。