SpringBoot集成websocket作为客户端和服务端的代码案例
以下是一个简单的Spring Boot集成WebSocket的示例。这个示例包括了一个简单的WebSocket服务端和客户端。
服务端代码:
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class WebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 连接建立后的处理逻辑
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的消息
System.out.println("Received message: " + message.getPayload());
// 可以选择向客户端发送消息
session.sendMessage(new TextMessage("Server received: " + message.getPayload()));
}
}
客户端代码:
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.net.URI;
public class WebSocketClient {
public static void main(String[] args) throws Exception {
URI uri = new URI("ws://localhost:8080/websocket"); // 替换为你的WebSocket服务端地址
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
// 可以添加认证头部等
WebSocketClient client = new StandardWebSocketClient();
WebSocketHandler handler = new TextWebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 连接建立后的处理逻辑
session.sendMessage(new TextMessage("Hello from client"));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 处理接收到的服务端消息
System.out.println("Received message: " + message.getPayload());
}
};
WebSocketSession session = client.doHandshake(handler, uri, headers).get();
// 这里可以继续发送消息或者等待关闭
// session.sendMessage(new TextMessage("Hello again"));
// 等待关闭或者其他逻辑
}
}
在这个例子中,服务端使用了TextWebSocketHandler
来处理消息,并打印接收到的消息。客户端连接到服务端
评论已关闭