複数クライアントの区別
server5.pdeとclient5.pdeでは、複数のクライアントが同時に接続している場合も、クライアントを区別せずに受け取った最も新しい座標で点の描画を行なっています。 これを、クライアントごとに座標を保持し、それぞれの点を描画するようにサーバープログラムを改良します。
サーバープログラムを以下のように書き換えます。
server6.pde
import processing.net.*;
class Point {
int x, y;
Point (int x, int y) {
this.x = x;
this.y = y;
}
}
Server myServer;
HashMap<Client, Point> points = new HashMap();
void setup() {
size(600, 600);
myServer = new Server(this, 5204);
}
void draw() {
background(255);
fill(0);
for (Point p : points.values()) {
ellipse(p.x, p.y, 10, 10);
}
}
void clientEvent(Client client) {
Point p = null;
while (client.available() > 0) {
String[] xy = split(client.readStringUntil('\n').trim(), ',');
p = new Point(int(xy[0]), int(xy[1]));
}
if (p != null) {
points.put(client, p);
}
}
void serverEvent(Server server, Client client) {
points.put(client, new Point(0, 0));
}
void disconnectEvent(Client client) {
points.remove(client);
}
HashMap<Client, Point>
型の points
を用いて、クライアントに対応した座標を保持するように変更しました。
serverEvent
でコネクションが確立されたときにクライアントに対応した Point
インスタンスを生成します。
clientEvent
でデータを受信したときには、クライアントに対応した座標を更新します。
disconnectEvent
でコネクションが切断されたときには、points
から対応するクライアントの座標情報を削除します。