How to determine when a client disconnected from the server

I have a program running on a server (Server A) that listens on one port for external connection (from an external server, B) and then listens on another port for internal connection on one server (server A), then it transfers data from the internal to the external connection and back.

I want to know if there is a way to detect that the external client has been disconnected. I just need one external connection at a time, but I would like to be able to accept a new one if the external client reboots or something like that.

This socket level stuff is completely insignificant for me, so if there is a better way around this, I’m all ears. One of the conditions is that the client running on server B must be the initiator of the connection, and the connection should work as long as possible.

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
source share
1 answer

If the client disconnects, readObject() will throw an EOFException , and write() will throw an IOException: connection reset . That is all you need.

0
source

Source: https://habr.com/ru/post/1437608/


All Articles