TooTallNate / Java-WebSocket

A barebones WebSocket client and server implementation written in 100% Java.
http://tootallnate.github.io/Java-WebSocket
MIT License
10.53k stars 2.58k forks source link

Is it possible to close connection if any exception or assertion failure occurs in main thread? #1320

Open Elvintest opened 1 year ago

Elvintest commented 1 year ago

Hello, i'm writing auto tests using your library as a transport for ws client. If any exception happens in runtime the main thread dies but some treads inside this webSocket client instance are still running and it doesn't allow my test to fall or finish successfully. System.exit() doesn't approach my aims. And i can't always catch exceptions and close connection manually, is there any setting to do it automatically in case of any any exception or assertion error in main test thread?

PhilipRoman commented 1 year ago

Can you please clarify your problem? What do you mean by "main thread"? If possible, add a small code example of what you're trying to achieve.

Elvintest commented 1 year ago

Sorry for a long pong of my side, practically i meant such cases: lets say we have such listener

   @Override
    public void onMessage(String message) {
        System.out.println("got: " + message); //temporary stdOut
        JsonNode treePackage;
        try {
            treePackage = objectMapper.readTree(message);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } 

If any Exception occurs in this block main thread of java program stops, but one of these internal threads in transport continues to be alive:

         /**
   * The thread to write outgoing message
   */
  private Thread writeThread;

  /**
   * The thread to connect and read message
   */
  private Thread connectReadThread;

I had solved my issue for destroying all threads by changing main logic of my programm, but i was wondering if there is any handler for shutting down all internal threads if i want it.Does close() function destroy both treads for reading and writing?

PhilipRoman commented 1 year ago

I would just catch the exception and call close(), it will correctly shut down all threads belonging to the client.