编写一个springboot websocket心跳包示例,并尽量加上注释。
时间: 2023-09-08 15:05:01 浏览: 108
Springboot+Websocket示例
### 回答1:
SpringBoot websocket心跳包示例:@ServerEndpoint("/websocket/{userId}")
public class MyWebSocket {
// 存放所有的连接会话
private static Map<Long, Session> webSocketMap = new ConcurrentHashMap<>();
// 心跳包超时时间,单位毫秒
private static final long HEART_BEAT_TIME_OUT = 1000;
@OnOpen
public void onOpen(@PathParam("userId") Long userId, Session session) {
webSocketMap.put(userId, session);
}
@OnMessage
public void onMessage(String message, Session session) {
// 收到客户端发来的消息,根据需要进行处理
}
@OnClose
public void onClose(Session session) {
Iterator<Map.Entry<Long, Session>> iterator = webSocketMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Long, Session> entry = iterator.next();
if (entry.getValue().equals(session)) {
iterator.remove();
}
}
}
@OnError
public void onError(Session session, Throwable error) {
webSocketMap.remove(session);
error.printStackTrace();
}
// 发送心跳包
private void sendHeartBeat() {
new Thread(() -> {
while (true) {
// 发送心跳
webSocketMap.forEach((k, v) -> {
// 心跳机制
try {
// 每隔一段时间向客户端发送一次心跳,表示服务器还在运行
v.getBasicRemote().sendText("HeartBeat");
Thread.sleep(HEART_BEAT_TIME_OUT);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
});
}
}).start();
}
}
### 回答2:
下面是一个使用Spring Boot和WebSocket实现心跳包示例的代码:
首先,我们需要在pom.xml文件中添加以下依赖项:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
```
接下来,我们创建一个WebSocket配置类,该类将配置WebSocket连接和处理程序:
```java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.setApplicationDestinationPrefixes("/app");
registry.enableSimpleBroker("/topic");
}
}
```
在此配置类中,我们将WebSocket连接绑定到`/ws`端点,启用SockJS支持,并启用消息代理。
接下来,我们创建一个处理心跳包的WebSocket处理程序:
```java
@Component
public class HeartbeatHandler extends TextWebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
logger.info("Received message: " + message.getPayload());
// 在这里处理心跳包逻辑
}
}
```
在此处理程序中,我们覆盖`handleTextMessage`方法来处理接收到的文本消息。在这个方法中,你可以编写你的心跳包逻辑。
最后,我们创建一个Spring Boot应用程序类来启动应用程序:
```java
@SpringBootApplication
public class WebSocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketApplication.class, args);
}
}
```
现在,你可以运行应用程序并在`/ws`端点上建立WebSocket连接。当接收到消息时,处理程序会调用`handleTextMessage`方法来处理心跳包逻辑。
希望这个示例对你有帮助。
### 回答3:
下面是一个使用Spring Boot编写的WebSocket心跳包示例:
```java
// 导入必要的包
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
//SpringBoot应用入口
@SpringBootApplication
//启用WebSocket和WebSocket STOMP消息代理支持
@EnableWebSocketMessageBroker
@EnableScheduling //启用定时任务
public class WebSocketHeartbeatApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketHeartbeatApplication.class, args);
}
//注册一个WebSocket端点,客户端可以通过这个端点连接到服务器
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
//WebSocket消息代理配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//设置消息代理前缀
registry.enableSimpleBroker("/topic");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//注册一个STOMP端点,客户端使用这个端点进行连接
registry.addEndpoint("/ws").setAllowedOrigins("*").setHandshakeHandler(new HttpSessionHandshakeHandler());
}
}
// WebSocket请求处理
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate template;
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/send")
@ResponseBody
public String send() {
template.convertAndSend("/topic/heartbeat", "心跳包:" + new Date());
return "消息已发送";
}
}
// 心跳包定时发送任务
@Component
public class HeartbeatTask {
@Autowired
private SimpMessagingTemplate template;
// 下面的注解表示每隔5秒钟执行该方法
@Scheduled(fixedRate = 5000)
public void sendHeartbeat() {
template.convertAndSend("/topic/heartbeat", "心跳包:" + new Date());
}
}
// 用户标识处理
@Component
public class HttpSessionHandshakeHandler extends HandshakeHandler {
@Override
protected boolean sameOriginDisabled() {
return true;
}
@Override
protected void doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws HandshakeFailureException {
// 将用户标识存储在WebSocket会话的attributes中
if (request instanceof ServletServerHttpRequest) {
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
HttpSession session = servletRequest.getSession();
if (session != null) {
User user = (User) session.getAttribute("user");
if (user != null) {
attributes.put("userId", user.getId());
}
}
}
}
}
}
```
上述示例中,首先我们在`WebSocketConfig`类中配置了一个`/ws`端点,客户端通过这个端点连接到服务器。接下来,在`WebSocketController`类中定义了发送消息的接口,客户端可以通过该接口发送消息。然后我们使用`HeartbeatTask`定时任务,每隔5秒钟向客户端发送一条心跳包。最后,在`HttpSessionHandshakeHandler`类中,我们将用户标识存储在WebSocket会话的attributes中,以便后续处理。
阅读全文