演習の解答例
演習1
import processing.net.*;
Server myServer;
void setup() {
  myServer = new Server(this, 80);
}
void draw() {
  Client client = myServer.available();
  if (client != null) {
    client.readString();
    client.write("HTTP/1.1 404 Not Found\r\n");
    client.write("\r\n");
    client.stop();
  }
}
演習2
import java.util.Iterator;
import processing.net.*;
Server myServer;
void setup() {
  myServer = new Server(this, 80);
}
void draw() {
}
void serverEvent(Server server, Client client) {
  Handler handler = new Handler(client);
  handler.start();
}
class Handler extends Thread {
  Client client;
  Handler(Client client) {
    this.client = client;
  }
  void run() {
    HeaderReader reader = new HeaderReader(this.client);
    String[] request = split(reader.next().trim(), ' ');
    println("Method : " + request[0]);
    println("Path : " + request[1]);
    println("Version : " + request[2]);
    String path = request[1].substring(1);
    if (path.length() == 0) {
      path = "index.html";
    }
    for (String line : reader) {
      String[] header = splitTokens(line.trim(), ": ");
      if (header.length == 2) {
        println(header[0] + " : " + header[1]);
      }
    }
    byte[] file = loadBytes(path);
    if (file == null) {
      this.client.write("HTTP/1.1 404 Not Found\r\n");
      this.client.write("\r\n");
      this.client.stop();
    } else {
      this.client.write("HTTP/1.1 200 OK\r\n");
      this.client.write("\r\n");
      this.client.write(file);
      this.client.stop();
    }
  }
}
class HeaderReader implements Iterable<String>, Iterator<String> {
  Client client;
  boolean stop = false;
  HeaderReader(Client client) {
    this.client = client;
  }
  Iterator<String> iterator() {
    return this;
  }
  boolean hasNext() {
    return !this.stop;
  }
  String next() {
    while (this.client.active()) {
      if (this.client.available() > 0) {
        String line = this.client.readStringUntil('\n');
        if (line != null) {
          if (line.equals("\r\n")) {
            this.stop = true;
          }
          return line;
        }
      }
    }
    return null;
  }
}