クライアントからサーバーへのデータ送信
これまでのプログラムは、クライアントはサーバーから送信されたデータを受信するだけでした。 次は、クライアントからサイバーへのデータ送信を行なってみましょう。
クライアントから受信したバイト数をサーバーで保持し、その数に応じて背景色を変更します。
以下のようなクライアントプログラムを作成します。
client4.pde
import processing.net.*;
Client myClient;
void setup() {
size(200, 200);
myClient = new Client(this, "127.0.0.1", 5204);
}
void draw() {
}
void mouseClicked() {
myClient.write(1);
}
クライアントからのデータ送信には Clientクラスの write
メソッドを使用します。
次に以下のようなサーバープログラムを作成します。
server4.pde
import processing.net.*;
Server myServer;
int val = 0;
void setup() {
size(200, 200);
myServer = new Server(this, 5204);
}
void draw() {
if (val % 3 == 0) {
background(255, 0, 0);
} else if (val % 3 == 1) {
background(0, 255, 0);
} else {
background(0, 0, 255);
}
}
void clientEvent(Client client) {
while (client.available() > 0) {
client.read();
val += 1;
}
}
サーバーでのクライアントからのデータ受信でも clientEvent
ハンドラを使用することに注意しましょう。