To create a WebSocket server, define a class annotated with @WsServerEndpoint. You can specify the path using the value attribute, which supports path variables (e.g., /websocket/{uid}/{arg}). Use lifecycle annotations to handle different WebSocket events.
@WsServerEndpoint(value = "/websocket/{uid}/{arg}")
public class ServerEndpoint {
@HandshakeBefore
public void before (HttpHeaders headers) {
System.out.println("before");
}
@OnOpen
public void open(Session session, @PathParam (value="uid") String uid, @PathParam String arg){
System.out.println("open");
session.sendText("hello client");
}
@OnMessage
public void onMessage(Session session, String message){
System.out.println("message:" + message);
session.sendText("server: " + message);
}
@OnClose
public void onClose(){
System.out.println("close " + LocalDateTime.now());
}
@OnError
public void onError(Session session, Throwable e) {
System.out.println("onError");
}
@OnEvent
public void onEvent(Session session, Object evt) {
if (evt instanceof IdleStateEvent) {
// Handle heartbeat/idle events
}
}
}