springboot使用websocket示例代码
时间: 2023-10-12 15:13:09 浏览: 178
以下是一个使用Spring Boot和WebSocket的示例代码:
1. 首先,在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建一个WebSocket配置类:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myWebSocketHandler(), "/my-websocket-endpoint").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myWebSocketHandler() {
return new MyWebSocketHandler();
}
}
```
3. 创建一个WebSocket处理程序:
```
public class MyWebSocketHandler implements WebSocketHandler {
private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
for (WebSocketSession s : sessions) {
s.sendMessage(message);
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
sessions.remove(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
sessions.remove(session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
```
4. 在控制器中注入WebSocketHandler:
```
@RestController
public class MyController {
@Autowired
private WebSocketHandler myWebSocketHandler;
@GetMapping("/send-message")
public void sendMessage(@RequestParam String message) {
TextMessage textMessage = new TextMessage(message);
try {
myWebSocketHandler.handleMessage(null, textMessage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
5. 在前端页面中使用JavaScript连接WebSocket:
```
var socket = new WebSocket('ws://localhost:8080/my-websocket-endpoint');
socket.onopen = function() {
console.log('WebSocket opened');
};
socket.onmessage = function(event) {
console.log('WebSocket message received: ' + event.data);
};
socket.onclose = function(event) {
console.log('WebSocket closed with code: ' + event.code);
};
socket.onerror = function(event) {
console.log('WebSocket error: ' + event.error);
};
```
这是一个简单的示例,您可以根据自己的需求进行修改。
阅读全文