06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Here is the entire client sketch:<br />

19.7<br />

Example 19-7: Client for multi-user whiteboard<br />

// Import the net libraries<br />

import processing.net.*;<br />

// Declare a client<br />

Client client;<br />

void setup() {<br />

size(200,200);<br />

// Create the Client<br />

client = new Client(this, "127.0.0.1", 5204);<br />

background(255);<br />

smooth();<br />

}<br />

void draw() {<br />

// If there is information available <strong>to</strong> read from the Server<br />

if (client.available() > 0) {<br />

// Read message as a String, all messages end with an asterisk<br />

String in = client.readStringUntil( '*');<br />

// Print message received<br />

println( "Receiving: " + in);<br />

// Split up the String in<strong>to</strong> an array of integers<br />

int[] vals = int(splitTokens(in, ",*"));<br />

// Render an ellipse based on those values<br />

fill(0,100);<br />

noStroke();<br />

ellipse(vals[0],vals[1],16,16);<br />

}<br />

}<br />

Data Streams 371<br />

// Send data whenever the user drags the mouse<br />

void mouseDragged() {<br />

// Put the String <strong>to</strong>gether with our pro<strong>to</strong>col: mouseX comma mouseY asterisk<br />

String out = mouseX + " ," + mouseY + " *";<br />

// Send the String <strong>to</strong> the server<br />

}<br />

client.write(out);<br />

// Print a message indicating we have sent data<br />

println("Sending: " + out);<br />

Multi-User Communication, Part 3: All Together Now<br />

When running a multi-user application, the order in which the elements are launched is important. Th e<br />

client sketches will fail unless the server sketch is already running.<br />

You should fi rst (a) identify the IP address of the server, (b) choose a port and add it <strong>to</strong> the server’s code,<br />

and (c) run the server.<br />

Afterward, you can launch the clients with the correct IP address and port.<br />

The client reads messages from<br />

the Server and parses them with<br />

splitTokens() according <strong>to</strong> our<br />

pro<strong>to</strong>col.<br />

A message is sent whenever the<br />

mouse is dragged. Note that a client<br />

will receive its own messages!<br />

Nothing is drawn here!

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!