Skip to content

Add a constructor to bind Server to a specific address (patch included) #2356

Description

@charlesgoyard

Hi,
I needed to have servers listening to:
10.0.1.3:2011
10.0.1.3:2012
10.0.1.3:2013
10.0.1.4:2011
10.0.1.4:2012
10.0.1.4:2013
on the same computer.
So I added a constructor to Server with : Server(PApplet parent, String host, int port). This is a bit advanced but it proved useful. Please include it in Processing if you like it :).

Thank you,
Charles

diff --git a/java/libraries/net/src/processing/net/Server.java b/java/libraries/net/src/processing/net/Server.java
index 12b73a7..2e80cb7 100644
--- a/java/libraries/net/src/processing/net/Server.java
+++ b/java/libraries/net/src/processing/net/Server.java
@@ -96,7 +96,45 @@ public class Server implements Runnable {
       //errorMessage("<init>", e);
     }
   }
+  /**
+   * @param parent typically use "this"
+   * @param host specific host/address to listen to
+   * @param port port used to transfer data
+   */
+  public Server(PApplet parent, String host, int port) {
+    this.parent = parent;
+    this.host = host;
+    this.port = port;

+    try {
+      InetAddress hostSocket = InetAddress.getByName(host);
+      server = new ServerSocket(this.port, 10, hostSocket);
+      //clients = new Vector();
+      clients = new Client[10];
+
+      thread = new Thread(this);
+      thread.start();
+
+      parent.registerMethod("dispose", this);
+
+      // reflection to check whether host applet has a call for
+      // public void serverEvent(Server s, Client c);
+      // which is called when a new guy connects
+      try {
+        serverEventMethod =
+          parent.getClass().getMethod("serverEvent",
+                                      new Class[] { Server.class,
+                                                    Client.class });
+      } catch (Exception e) {
+        // no such method, or an error.. which is fine, just ignore
+      }
+
+    } catch (IOException e) {
+      e.printStackTrace();
+      thread = null;
+      //errorMessage("<init>", e);
+    }
+  }

   /**
    * ( begin auto-generated from Server_disconnect.xml )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions