import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/websocket")
public class WebSocketTest {
private static final CopyOnWriteArraySet<Session> sessions = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
System.out.println("Connected ... " + session.getId());
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
System.out.println("Disconnected ... " + session.getId());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("Error ... " + session.getId());
throwable.printStackTrace();
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("Received message ... " + session.getId() + " " + message);
for (Session peer : sessions) {
if (!peer.equals(session)) {
try {
peer.getBasicRemote().sendText(message);
} catch (IOException e) {
onError(peer, e);
}
}
}
}
}
这段代码使用Java定义了一个简单的WebSocket服务端点,它可以处理多个客户端的连接,并将接收到的消息广播到所有其他的客户端。这个例子展示了如何使用Java EE的WebSocket API,并且如何处理连接、消息接收、错误以及关闭事件。