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.

366 <strong>Learning</strong> <strong>Processing</strong><br />

19.5<br />

Example 19-5: Client reading values as rotation value<br />

// Import the net libraries<br />

import processing.net.*;<br />

// Declare a client<br />

Client client;<br />

// The data we will read from the server<br />

int data;<br />

void setup() {<br />

size(200,200);<br />

smooth();<br />

// Create the Client<br />

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

}<br />

void draw() {<br />

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

data = client.read(); // Read data<br />

}<br />

background(255);<br />

stroke(0);<br />

fill(175);<br />

translate(width/2,height/2);<br />

float theta = (data/255.0) * TWO_PI;<br />

rotate(theta);<br />

rectMode(CENTER);<br />

rect(0,0,64,64);<br />

}<br />

The incoming data is<br />

used <strong>to</strong> rotate a square.<br />

Exercise 19-3: Write a client that uses the number broadcast from the server <strong>to</strong> control the<br />

location of a shape.<br />

Multi-User Communication, Part 1: The Server<br />

Th e broadcast example demonstrates one-way communication where a server broadcasts a message and<br />

many clients receive that message. Th e broadcast model, however, does not allow a client <strong>to</strong> turn around<br />

and send a reply back <strong>to</strong> the server. In this section, we will cover how <strong>to</strong> create a sketch that involves<br />

communication between multiple clients facilitated by a server.<br />

Let’s explore how a chat room works. Five clients (you and four friends) connect <strong>to</strong> a server. One client<br />

types a message: “ Hey everyone! ” Th at message is sent <strong>to</strong> the server, which relays it back <strong>to</strong> all fi ve clients.<br />

Most multi-user applications function in a similar fashion. A multiplayer online game, for example,<br />

would likely have clients sending information related <strong>to</strong> their whereabouts and actions <strong>to</strong> a server that<br />

broadcasts that data back <strong>to</strong> all other clients playing the game.<br />

A multi-user application can be developed in <strong>Processing</strong> using the network library. To demonstrate, we<br />

will create a networked, shared whiteboard. As a client drags its mouse around the screen, the sketch

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

Saved successfully!

Ooh no, something went wrong!