# Processing Net : avoid print disconnection message

**URL:** <https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513>\
**Category:** Libraries\
**Created:** [July 5, 2018, 10:31am UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513 "2018-07-05T10:31:56Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![Honny](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/honny/32/672_2.png) [@Honny](https://discourse.processing.org/u/Honny)\
**Post date:** [July 5, 2018, 10:31am UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/1 "2018-07-05T10:31:56Z")

</div>

Hello,  
im writing a simple program using the Processing Net library, this program should be able to start/stop a TCP server on a given port.

I have noticed that calling voluntarily the stop() function i receive in the console output the following message :  
Server SocketException: socket closed

test case :

```auto
import processing.net.*;

Server server;

void setup() 
{
    size(200, 200);
    
    try 
    {
        server = new Server(this, 3273); 
    }
    catch (Exception exception) {println("PORT ALREADY IN USE");};
}

void draw() 
{
background(color(0,0,0));
             
}

/ ****************************** /
void keyTyped() 
{
    server.stop();
}

```

---

<div class="post-metadata">

**Author:** ![Honny](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/honny/32/672_2.png) [@Honny](https://discourse.processing.org/u/Honny)\
**Post date:** [July 5, 2018, 10:40am UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/2 "2018-07-05T10:40:32Z")

</div>

In my specific case i want to avoid this print because it is me that voluntatly want to close the server.

I tryed to extend the Server class as :

```auto
class HServer extends Server
{
    HServer(PApplet parent, int port) 
    {
        super(parent, port, null);
    }
    
    public void dispose() 
    {
        thread = null;

        if (clients != null) 
        {
          disconnectAll();
          clientCount = 0;
          clients = null;
        }

        try 
        {
          if (server != null) 
          {
            server.close();
            server = null;
          }
        } 
        catch (IOException e) 
        {
          //e.printStackTrace();
        }
    }

}

```

like you can see im just commenting out the e.printStackTrace(); and adding the constructor because there is not implicit constructor in Server class

But this solution doesnt work because the field Server.thread is not visible.

I could replace the entire Server class but it doesnt make sense to me.

Do you have some advice ?

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![kfrajer](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kfrajer/32/196_2.png) [@kfrajer](https://discourse.processing.org/u/kfrajer)\
**Post date:** [July 5, 2018, 2:01pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/3 "2018-07-05T14:01:10Z")

</div>

This package is built when building Processing. For a short immediate solution if **this was** an isolated library, one could rebuild it with the single line change aka. removing the `print()` statement. For this case, I think you would need to re-build Processing. This could be easier than just trying to figure out what java files you need to modify related to the `processing.net` package. Maybe it is not difficult to isolate them but I haven’t tried that before.

For a better and long term solution, you could submit a ticket in github. However, it might take some time before they provide a solution.

On a side note, the message shows up in the console. An easier approach is to ignore the messages all together. I mean, it is not interfering with your code or demonstrations, or is it?

Kf

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [July 5, 2018, 3:12pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/4 "2018-07-05T15:12:42Z")

</div>

IMO, library devs do a big disservice to the Processing community (who are very tweaky by nature 🙃) by using the keyword `private` or leaving the default package access level. 🤧

As we can confirm from class Server’s source code: 🤖

> <https://github.com/processing/processing/blob/master/java/libraries/net/src/processing/net/Server.java#L55-L56>

Both fields _thread_ & _server_ were left as package-protected access level. And many other fields as well btW! 🙄

We could use reflection to force access to them all. But it’s too convoluted & a hassle! 😴

A much clever workaround is to make a “.java” file for our “hacked” Server subclass, which is HServer. 🕶

And then “lie” that the “HServer.java” file belongs to `package` “[processing.net](http://processing.net)” too! 😈

All of a sudden all those package-protected members become accessible to our custom HServer subclass! 🤑

Here’s my take on that: 😇

## “HServer.java”

```auto
package processing.net;

import java.io.IOException;
import processing.core.PApplet;

public class HServer extends Server {
  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() {
    thread = null;

    if (clients != null) {
      disconnectAll();
      clientCount = 0;
      clients = null;
    }

    try {
      if (server != null) {
        server.close();
        server = null;
      }
    }

    catch (final IOException e) {
      //e.printStackTrace();
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [July 5, 2018, 4:14pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/5 "2018-07-05T16:14:39Z")

</div>

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

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

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

> <https://github.com/processing/processing/blob/master/java/libraries/net/src/processing/net/Server.java#L321-L323>

> Thrown when `server.close();` is called and _server_ is waiting on **accept()**.

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

> <https://github.com/processing/processing/blob/master/java/libraries/net/src/processing/net/Server.java#L287-L291>

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: 😩

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

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

## “HServer.java”

```auto
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;
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![Honny](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/honny/32/672_2.png) [@Honny](https://discourse.processing.org/u/Honny)\
**Post date:** [July 5, 2018, 9:27pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/6 "2018-07-05T21:27:21Z")

</div>

@kfrajer @GoToLoop first of all thanks to both of you for your time .

Ill try to explaine a little more my “weird” question and the solution i have found after your suggestions

CASE SCENARIO :

- the thread is blocked waiting on accept()
- an socket exception is thrown  
QUESTION :
- Who has launched the exception ?  
ANSWER :
- it’s me stopping the server —\> OK, dont print nothing we know it
- it is a real network problem —\> ERROR, print the stack trace

As you can see my goal is to distinguish two separate cases and handle them of consequence .

As suggested i worked on the HServer.java file and extended the class.

As solution i added a boolean variable named “stopIsRequested” and overrided stop() and run() method with minimal difference from the original source code as follow :

```auto
package processing.net;

import processing.core.*;

import java.io.*;
import java.lang.reflect.*;
import java.net.*;

public class HServer extends Server 
{
    boolean stopIsRequested ;
    
    
    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 stop() 
    {
    this.stopIsRequested = true ;
    dispose();
    }
    
@Override public void run() {
    
    this.stopIsRequested = false;
    
    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);
        synchronized (clientsLock) {
          addClient(client);
          if (serverEventMethod != null) {
            try {
              serverEventMethod.invoke(parent, this, client);
            } catch (Exception e) {
              System.err.println("Disabling serverEvent() for port " + port);
              Throwable cause = e;
              // unwrap the exception if it came from the user code
              if (e instanceof InvocationTargetException && e.getCause() != null) {
                cause = e.getCause();
              }
              cause.printStackTrace();
              serverEventMethod = null;
            }
          }
        }
      } catch (SocketException e) {
        //thrown when server.close() is called and server is waiting on accept
        if( ! stopIsRequested ) { System.err.println("Server SocketException: " + e.getMessage()); };
        thread = null;
      } catch (IOException e) {
        //errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
    }
    }
}

```

what you think about this ?

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [July 5, 2018, 9:44pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/7 "2018-07-05T21:44:02Z")

</div>

Apart from the messy lack of indentation, it looks gr8! 👍

However, if we directly invoke Server::**dispose()** instead of Server::**stop()**, your _stopIsRequested_ “trap” is skipped! 😨

So you should place it inside Server::**dispose()** instead; given Server::**stop()** is merely an alias of it. 😉

BtW, no need to prefix _stopIsRequested_ w/ keyword `this` in Java: ☕  
Just `stopIsRequested = true;` works alright! 😇

P.S.: I’ve edited & included the _stopRequested_ flag to my own version too! 🤪

---

<div class="post-metadata">

**Author:** ![Honny](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/honny/32/672_2.png) [@Honny](https://discourse.processing.org/u/Honny)\
**Post date:** [July 5, 2018, 10:17pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/8 "2018-07-05T22:17:11Z")

</div>

> [@GoToLoop](#):
>
> However, if we directly invoke Server:: **dispose()** instead of Server:: **stop()** , your _stopIsRequested_ “trap” is skipped! 😨
> 
> So you should place it inside Server:: **dispose()** instead; given Server:: **stop()** is merely an alias of it.

You are right !  
unfortunatly in one of the costructor of the original server class there is :

> 96: parent.registerMethod(“dispose”, this);

and according to processing documentation :

```auto
public void dispose() {
    // Anything in here will be called automatically when 
    // the parent sketch shuts down. For instance, this might
    // shut down a thread used by this library.
  }

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [July 5, 2018, 10:32pm UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/9 "2018-07-05T22:32:35Z")

</div>

But then, if the sketch is closed by the user, rather than by an explicit call to Server::stop(), that red “Server SocketException: socket closed” message is displayed if the flag isn’t set within Server::dispose()! 😩

I was under the impression you wanted to eliminate that message if there’s no actual error. 🤔

The way your version is set up, normal sketch closing always results in that message error. 😲

---

<div class="post-metadata">

**Author:** ![Honny](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/honny/32/672_2.png) [@Honny](https://discourse.processing.org/u/Honny)\
**Post date:** [July 6, 2018, 5:51am UTC](https://discourse.processing.org/t/processing-net-avoid-print-disconnection-message/1513/10 "2018-07-06T05:51:33Z")

</div>

sorry for my poor english, i mean you are correct, the true assignement should be done in dispose() , NOT in stop().

so the final form of our class should be :

```auto
package processing.net;

import processing.core.*;

import java.io.*;
import java.lang.reflect.*;
import java.net.*;

public class HServer extends Server 
{
  boolean stopIsRequested ;

  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 run() {

    stopIsRequested = false;

    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);
        synchronized (clientsLock) {
          addClient(client);
          if (serverEventMethod != null) {
            try {
              serverEventMethod.invoke(parent, this, client);
            } 
            catch (Exception e) {
              System.err.println("Disabling serverEvent() for port " + port);
              Throwable cause = e;
              // unwrap the exception if it came from the user code
              if (e instanceof InvocationTargetException && e.getCause() != null) {
                cause = e.getCause();
              }
              cause.printStackTrace();
              serverEventMethod = null;
            }
          }
        }
      } 
      catch (SocketException e) {
        //thrown when server.close() is called and server is waiting on accept
        if ( ! stopIsRequested ) { 
          System.err.println("Server SocketException: " + e.getMessage());
        };
        thread = null;
      } 
      catch (IOException e) {
        //errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
    }
  }

  @Override public void dispose() {

    stopIsRequested = true;

    thread = null;

    if (clients != null) {
      disconnectAll();
      clientCount = 0;
      clients = null;
    }

    try {
      if (server != null) {
        server.close();
        server = null;
      }
    } 
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

```

Thx very much for the support .  
I hope this could help someone else in the same situation in the future .  
Cya ! 😉
