Hardware Reference
In-Depth Information
First, start with the
variable declarations and
definitions. The main variables are an
instance of the Server class, a port
number to serve on, and an ArrayList
to keep track of the clients.
Try It
/*
Test Server Program
Context: Processing
Creates a server that listens for clients and prints
what they say. It also sends the last client anything that's
typed on the keyboard.
*/
// include the net library:
import processing.net.*;
int port = 8080; // the port the server listens on
Server myServer; // the server object
ArrayList clients = new ArrayList(); // list of clients
8 This program uses a data type you may not have seen before: ArrayList . Think of it as a super-
duper array. ArrayLists don't have a fixed number of elements to begin with, so you can add new
elements as the program continues. It's useful when you don't know how many elements you'll have.
In this case, you don't know how many clients you'll have, so you'll store them in an ArrayList, and
add each new client to the list as it connects. ArrayLists include some other useful methods. There
is an introduction to ArrayLists on the Processing website at www.processing.org.
The setup() method starts the
server.
8
void setup()
{
myServer = new Server(this, port);
}
The draw() method listens for new
messages from clients and prints
them. If a client says "exit," the server
disconnects it and removes it from the
list of clients.
8
void draw()
{
// get the next client that sends a message:
Client speakingClient = myServer.available();
if (speakingClient !=null) {
String message = trim(speakingClient.readString());
// print who sent the message, and what they sent:
println(speakingClient.ip() + "\t" + message);
if (message.equals("exit")) {
myServer.disconnect(speakingClient);
clients.remove(speakingClient);
}
}
}
 
Search WWH ::




Custom Search