Processing Net : avoid print disconnection message

However, the red message “Server SocketException: socket closed” still shows up! :exploding_head:

Your assumption that commenting out e.printStackTrace(); within method dispose() would get rid of it is wrong! :ghost:

According to the comment right there at the SocketException catch () {} block within method run(): :thinking:

Thrown when server.close(); is called and server is waiting on accept().

Method dispose() invokes server.close(); right here:

However, there’s nothing we can do from within Server::dispose(), b/c ServerSocket::close() method always throws a SocketException when ServerSocket::accept() is active: :weary:

  1. https://Docs.oracle.com/javase/10/docs/api/java/net/ServerSocket.html#close()
  2. ServerSocket (Java SE 10 & JDK 10 )
  3. SocketException (Java SE 10 & JDK 10 )

So the only workaround left is hacking Server::run() rather than Server::dispose(): :space_invader:

“HServer.java”

package processing.net;

import java.net.Socket;
import java.net.SocketException;
import java.io.IOException;

import processing.core.PApplet;

public class HServer extends Server {
  protected boolean stopRequested;

  public HServer(PApplet parent, int port) {
    this(parent, port, null);
  }

  public HServer(PApplet parent, int port, String host) {
    super(parent, port, host);
  }

  @Override public void dispose() {
    stopRequested = true;
    super.dispose();
  }

  @Override public void run() {
    while (Thread.currentThread() == thread) try {
      final Socket socket = server.accept();
      final Client client = new Client(parent, socket);

      //synchronized (clients) { // for Processing 3.3.6 and older!
      synchronized (clientsLock) { // for Processing 3.3.7 and newer!
        addClient(client);

        if (serverEventMethod != null) try {
          serverEventMethod.invoke(parent, this, client);
        }

        catch (final ReflectiveOperationException e) {
          System.err.println("Disabling serverEvent() for port " + port);
          serverEventMethod = null;

          final Throwable cause = e.getCause();
          (cause != null? cause : e).printStackTrace();
        }
      }
    }

    catch (final SocketException e) {
      // Thrown when server.close()'s called & server's waiting on accept():
      if (!stopRequested)
        System.err.println("Server SocketException: " + e.getMessage());
      thread = null;
    }

    catch (final IOException e) {
      e.printStackTrace();
      thread = null;
    }
  }
}