java实现websocket实现消息推送
时间: 2023-12-01 19:42:15 浏览: 165
Java实现WebSocket实现消息推送的步骤如下:
1.创建WebSocket配置类
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyWebSocketHandler(), "/websocket").addInterceptors(new MyHandshakeInterceptor());
}
}
```
2.创建WebSocket处理器
```java
public class MyWebSocketHandler extends TextWebSocketHandler {
private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession s : sessions) {
s.sendMessage(message);
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
```
3.创建握手拦截器
```java
public class MyHandshakeInterceptor implements HandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
return true;
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
```
4.在页面中使用JavaScript连接WebSocket
```javascript
var socket = new WebSocket("ws://localhost:8080/websocket");
socket.onmessage = function(event) {
console.log(event.data);
};
```
阅读全文