Quantcast
Channel: Processing Forum
Viewing all articles
Browse latest Browse all 1768

Re : How do I send data to only one client (using the network library)? [SOLVED!]

$
0
0
Wow! Thank you so much dimkir, it works perfectly! You're the best! I thought for sure I was screwed, I had no idea you could do clientName.write() in the server program!
Also thanks for contributing and mentioning Wireshark, PhiLho, I still have a lot to learn about networking, so any information like that is really helpful.

If anyone wants to see my implementation (which, warning, is just an example, and could probably be improved upon), here it is:

Server:
  1. //Example code for a server with multiple clients communicating to only one at a time.
  2. import processing.net.*;
  3. Server mainServer;
  4. int val[] = new int[0];
  5. Client c[] = new Client[0];//the array of clients
  6. void setup() {
  7.   size(200, 200);
  8.   mainServer = new Server(this, 5204);
  9.   noStroke();
  10.   val = expand(val, val.length+1);
  11. }
  12. void draw() {
  13.   background(0);
  14.   textAlign(CENTER);
  15.   text(c.length, width/2., height/2.);//Displays how many clients have connected to the server
  16.   for (int i = 0; i < c.length; i++)
  17.   {
  18.     val[i] = (val[i]+i+1)%255;//changes the value based on which client number it has (the higher client number, the fast it changes).
  19.     c[i].write(byte(val[i]));//writes to the right client (using the byte type is not necessary)
  20.     text(val[i], width/2., height/2.+15*(i+1));
  21.   }
  22. }
  23. void serverEvent(Server srvr, Client clnt)//Called when a client connects.
  24. {
  25.   c = (Client[]) expand(c, c.length+1);//expand the array of clients
  26.   c[c.length-1] = clnt;//sets the last client to be the newly connected client
  27.   doStuff();
  28. }
  29. void doStuff()//this is extra stuff that can be done,
  30. {//in this case expanding a value array to have a value for each client.
  31.   val = expand(val, val.length+1);
  32. }

And it will work for any client. My particular client code is basically just a copy of the example (which helps demonstrate that each client is indeed getting its own data):

  1. import processing.net.*;
  2.     Client myClient;
  3.     int dataIn;
  4.     void setup() {
  5.       size(200, 200);
  6.       myClient = new Client(this, "127.0.0.1", 5204);
  7.     }
  8.     void draw() {
  9.       textAlign(CENTER);
  10.       background(0);
  11.       background(dataIn);
  12.      
  13.       text("Client #clientNumber data: "+int(dataIn), width/2., height/2.);// you can replace clientNumber with whatever number you wish
  14.       fill(255,0,0);
  15.       for(int i = 0; true; i++)
  16.       {
  17.         if (myClient.available() > 0) {
  18.           dataIn = myClient.read();
  19.         }
  20.         else
  21.         break;
  22.       }
  23.     }

Viewing all articles
Browse latest Browse all 1768

Trending Articles