WebSocket 详解--spring boot简单使用案例
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class MyWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("Connected ... " + session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
System.out.println("Received message: " + message.getPayload());
session.sendMessage(new TextMessage("Response message"));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("Transport error " + session.getId() + ":" + exception.getMessage());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("Connection closed " + session.getId());
}
}
这段代码定义了一个WebSocket处理器MyWebSocketHandler
,它继承自TextWebSocketHandler
。在连接建立、接收消息、处理传输错误以及连接关闭时,它提供了相应的处理逻辑。这个例子展示了如何在Spring Boot应用中使用WebSocket,并简单处理文本消息。
评论已关闭