WebSocket详解(Java后端,基于Springboot)
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("Hello, client!"));
}
@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());
}
}
这段代码定义了一个MyWebSocketHandler
类,它继承自TextWebSocketHandler
。在这个类中,我们覆盖了四个方法:afterConnectionEstablished
、handleTextMessage
、handleTransportError
和afterConnectionClosed
。这些方法分别在WebSocket连接建立、接收消息、传输发生错误和连接关闭时被调用。在handleTextMessage
方法中,我们接收到消息后,向客户端发送了一个问候消息。这个例子展示了如何在WebSocket连接中使用Spring Boot处理文本消息。
评论已关闭