I found a practical usage.
- It can be operated through threads.
- It can accept multiple users.
- It was processed using ‘serverEvent’.
It works pretty well, thank you.
import processing.net.*;
import java.util.concurrent.CopyOnWriteArrayList;
Server server;
CopyOnWriteArrayList<Client> clients = new CopyOnWriteArrayList<Client>();
void setup() {
size(400, 400);
server = new Server(this, 5204);
println("서버 시작됨 (포트 5204)");
Thread serverThread = new Thread(new Runnable() {
public void run() {
handleClients();
}
});
serverThread.start();
}
void draw() {
background(200);
text("클라이언트 수: " + clients.size(), 20, 30);
}
// 새로운 클라이언트가 접속되었을 때 호출
void serverEvent(Server someServer, Client newClient) {
println("접속됨: " + newClient.ip());
clients.add(newClient);
}
// 비동기 메시지 수신 + 응답 + 연결 종료 처리
void handleClients() {
while (true) {
for (Client c : clients) {
if (!c.active()) {
println("클라이언트 연결 해제됨: " + c.ip());
clients.remove(c);
continue;
}
if (c.available() > 0) {
String msg = c.readStringUntil('\n');
if (msg != null) {
msg = msg.trim();
println("[" + c.ip() + "] 받은 메시지: " + msg);
// 1) 답문 (예: Echo)
String reply = "서버 응답: " + msg + "\n";
c.write(reply);
println("[" + c.ip() + "] 답문 전송 완료");
// 2) 특정 키워드가 오면 통신 끊기
if (msg.equalsIgnoreCase("bye")) {
println("[" + c.ip() + "] 연결 종료됨 (bye 명령)");
c.stop(); // 연결 종료
clients.remove(c); // 리스트에서 제거
}
}
}
}
delay(10);
}
}