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.

Data Streams 369<br />

Here is the full Server with some bells and whistles. A message is displayed onscreen when new clients<br />

connect as well as when the server receives data.<br />

19.6<br />

Example 19-6: Multi-user server<br />

// Import the net libraries<br />

import processing.net.*;<br />

// Declare a server<br />

Server server;<br />

PFont f;<br />

String incomingMessage = " " ;<br />

void setup() {<br />

size(400,200);<br />

// Create the Server on port 5204<br />

server = new Server(this, 5204);<br />

f = createFont( "Arial",20,true);<br />

}<br />

void draw() {<br />

background(255);<br />

// Display rectangle with new message color<br />

fill(0);<br />

textFont(f);<br />

textAlign(CENTER);<br />

text(incomingMessage,width/2,height/2);<br />

// If a client is available, we will find out<br />

// If there is no client, it will be "null"<br />

Client client = server.available();<br />

// We should only proceed if the client is not null<br />

if (client ! = null) {<br />

// Receive the message<br />

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

// Print <strong>to</strong> <strong>Processing</strong> message window<br />

println( "Client says: " + incomingMessage);<br />

// Write message back out (note this goes <strong>to</strong> ALL clients)<br />

server.write(incomingMessage);<br />

}<br />

}<br />

// The serverEvent function is called whenever a new client connects.<br />

void serverEvent(Server server, Client client) {<br />

incomingMessage = " A new client has connected: " + client.ip();<br />

println(incomingMessage);<br />

}<br />

Multi-User Communication, Part 2: The Client<br />

Th e client’s job is three-fold:<br />

1. Send mouseX and mouseY coordinates <strong>to</strong> server.<br />

2. Retrieve messages from server.<br />

3. Display ellipses in the window based on server messages.<br />

All messages received from<br />

one client are immediately<br />

relayed back out <strong>to</strong> all<br />

clients with write().

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

Saved successfully!

Ooh no, something went wrong!