Server->client reply

So I have something you can use. I didn’t go into the source code but I did a layer on top to keep track of the clients on the server side, and for the clients to remember what id they each get assigned by the server during the connection process.

IMPORTANT: Do not stop the sketch using the stop button in the PDE. Instead, close the sketch only by hitting/clicking the x button in the sketch window. To fix this issue, a proper exit() function needs to be implemented. Not important at the moment but just keep in mind.

Notice also it is very important that the server is open first followed by the clients, and likewise, the server is closed last.

When a client connects to the server, the client receives a tag id from the server which the client stores internally. The server keeps track of these tags.

If you click in the client’s sketch, it send a message to the server and the sender relays this msg back to the client.

when a client disconnects (the sketch window is closed via the x button of the sketch window), the client issues a disconnection which is captured by the server. The server proceeds to remove the id from the mist of connected clients.

While running this code, server-client connection failed few times which affected my mouseEvents in Windows. Hopefully mouseEvents work for you.

Kf

P.S. You can run multiple clients. Just assigned a diff color to each sketch.

SERVER


// Creates a server that prints new client's IP addresses. 

import processing.net.*;

final String SEP=":";

int port = 12009;   
Server myServer;   

IntList myClientsList;

void setup()
{
  size(400, 400);
  myServer = new Server(this, port); // Starts a server on port 10002
  fill(220);
  textSize(18);
  myClientsList=new IntList();
}

void draw() {
  // Nothing happens here, everything happens inside ServerEvent()
  background(180, 0, 0);
  text("Server", 0, height/2);

  // Get the next available client
  Client thisClient = myServer.available();
  // If the client is not null, and says something, display what it said
  if (thisClient !=null) {

    String whatClientSaid = thisClient.readString();
    println("Received from client at " + millis()+" ms");

    if (whatClientSaid != null) {

      String[] lines=split(whatClientSaid, SEP);

      if (lines.length==1) {

        println(thisClient.ip() + " says >>" + whatClientSaid + "<<");
        myServer.write(str(frameCount));
      } else if (lines.length==2) {

        if (lines[0].equals("disconnect")) {
          int clientid=int(trim(lines[1]));

          if (myClientsList.hasValue(clientid)) {
            //Removes clientid located in array at index based on index() function
            myClientsList.remove(myClientsList.index(clientid));
            println("Client #"+clientid+" was removed. Number of clients connected=" + myClientsList.size());
          } else {
            //Something seriously wrong
            println("FATAL server error. Client id#"+clientid+" issue disconnection but not found in server. Why?");
          }
        }//Processing two tokes: disconnection
      } else {
        println("FATAL server error. I got more than two tokens during parsing msg. Why?");
      }
    }
  }  // thisClient !=null
}

// ServerEvent message is generated when a new client connects 
// to an existing server.
void serverEvent(Server someServer, Client someClient) {
  println("We have a new client: " + someClient.ip());

  //Generate random index as we have a new client. Ensures indes is not assigned
  int clientid=-1;  //Not assigned
  while (clientid<0 || myClientsList.hasValue(clientid))
    clientid=int(random(1)*100000);

  myClientsList.append(clientid);
  myClientsList.sort();
  someClient.write("helloWithID"+SEP+clientid);
  println("WELCOME client #"+clientid+". Current clients in queu:"+myClientsList.size());
  printArray(myClientsList.array());
}

CLIENT

import processing.net.*;

final String SEP=":";

Client c;

int clientid=-1;  //Not assigned


void setup() {
  size(400, 200);
  fill(220);
  textSize(18);
  c = new Client(this, "192.168.1.67", 12009); // Connect to server on port 8080
}

void draw() {
  background(0, 180, 0);
  text("Client", 0, height/2);

  if (c.available() > 0) { 

    // Read in the bytes
    byte[] byteBuffer = new byte[1024];
    int byteCount = c.readBytes(byteBuffer); 
    if (byteCount > 0 ) {
      // Convert the byte array to a String
      String myString = new String(byteBuffer);

      println("Received from server at " + millis()+" ms");

      String[] lines=split(myString, SEP);

      if (lines.length==1) {
        println(c.ip() + " says >>" + myString + "<<");
        c.write(str(frameCount));
        
      } else if (lines.length==2) {

        if (lines[0].equals("helloWithID")) {
          clientid=int(trim(lines[1]));
          println("Assigned id ta#"+clientid+" by server.");
        }//Processing two tokes: disconnection
      } else {
        clientid=  -99;
        println("FATAL client error. I got more than two tokens during parsing msg. Why?");
      }
    }  //byteCount>0
  }
}

void mouseReleased() {
  c.write(str(frameCount));
  println("Send=>" + str(frameCount));
}

void exit() {
  disconnectEvent(c);
}

void disconnectEvent(Client someClient) {

  print("Server Says:  ");
  int dataIn = someClient.read();

  println("DISCONNECTION issued: " + clientid);
  someClient.write("disconnect"+SEP+clientid);
  println("Read from server=>" +dataIn);
}
1 Like