代码实现springboot创建WebSocket服务端和网页客户端
时间: 2023-02-16 18:23:55 浏览: 122
在Spring Boot中创建WebSocket服务端需要使用spring-boot-starter-websocket依赖和@EnableWebSocket注解。
1. 在pom.xml中添加依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 创建WebSocket配置类,并使用@EnableWebSocket注解:
```
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
```
3. 创建WebSocket服务端类,并使用@ServerEndpoint注解:
```
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) {
// ...
}
@OnMessage
public void onMessage(String message, Session session) {
// ...
}
@OnClose
public void onClose() {
// ...
}
@OnError
public void onError(Throwable error) {
// ...
}
}
```
网页客户端可以使用JavaScript的WebSocket API连接到WebSocket服务端。
1. 创建WebSocket对象:
```
var socket = new WebSocket("ws://localhost:8080/ws/123456");
```
2. 设置连接打开和消息接收事件监听:
```
socket.onopen = function(event) {
console.log("WebSocket connected!");
};
socket.onmessage = function(event) {
console.log("WebSocket message received: " + event.data);
};
```
3. 发送消息:
```
socket.send("Hello Server!");
```
4. 关闭连接:
```
socket.close();
```
注意: 上面给出的代码只是简单的示例,在实际应用中需要根据需要进行完善。
阅读全文
相关推荐
















