public void sendWorkToServer(Object obj) {
//
logger.info(this.getClass().getSimpleName() + " >>> Enter sendWorkToServer");
if (webSocketSession == null || !webSocketSession.isOpen()) {
setUp();
}
if (obj == null || obj.getId() == null || obj.getId().isEmpty()) {
return;
}
ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
logger.info(json);
webSocketSession.getAsyncRemote().sendText(json);
//messageLatch.await(500, TimeUnit.MILLISECONDS);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
logger.info("Socket is open: " + webSocketSession.isOpen());
logger.info("Exit sendWorkToServer");
}
private boolean setUp() { //Called if needed inside sendWorkToServer() method
try {
websocketServerURI = serverSocketURI.getAddCfgStructureWsUri(); // Get Correct URI Development vs Production
logger.info("URI: " + websocketServerURI.toString());
webSocketContainer = ContainerProvider.getWebSocketContainer(); // WebSocket Container
webSocketSession = webSocketContainer.connectToServer(this.getClass(), websocketServerURI); // Connect to the Server
if (!webSocketSession.isOpen()) {
messageLatch.await(10, TimeUnit.SECONDS);
}
} catch (DeploymentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
public boolean tearDown() {
if (webSocketSession != null) {
if (webSocketSession.isOpen()) {
try {
webSocketSession.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
webSocketSession = null;
webSocketContainer = null;
websocketServerURI = null;
serverSocketURI = null;
return true;
}
So, inside my other object the code looks something like...
Also, what might be helpful is to add a custom method that just return the status of your websocketclient session and then call teardown() as needed.
I hope that helps a bit... In my scenario I take some extra steps to control the life cycle so I don't really have to detect status.