springboot配置WebSocket的demo
时间: 2023-11-21 08:04:45 浏览: 108
SpringBoot.WebSocket-demo
好的,以下是一个简单的Springboot配置WebSocket的DEMO:
1. 配置依赖
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
2. 配置Endpoint
```
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/websocket", configurator = SpringConfigurator.class)
@Component
public class WebSocketServer {
//连接建立成功调用
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket连接建立成功!");
}
//连接关闭调用
@OnClose
public void onClose() {
System.out.println("WebSocket连接关闭!");
}
//接收到客户端消息时调用
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("接收到来自客户端的消息:" + message);
sendMessage("已经接收到您发送的消息:" + message, session);
}
//发生错误时调用
@OnError
public void onError(Session session, Throwable error) {
System.out.println("WebSocket发生错误:" + error.getMessage());
}
//发送消息
public void sendMessage(String message, Session session) {
try {
session.getBasicRemote().sendText(message);
} catch (Exception e) {
System.out.println("发送消息出错:" + e.getMessage());
}
}
}
```
3. 配置WebSocket配置类
```
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
```
4. 测试
```
//客户端代码
var ws = new WebSocket("ws://localhost:8080/websocket");
ws.onopen=function(event){
console.log("WebSocket连接建立成功!");
ws.send("Hello WebSocket!");
}
ws.onmessage=function(event){
console.log("接收到服务端的消息:"+event.data);
}
ws.onclose=function(event){
console.log("WebSocket连接关闭!");
}
```
这是一个简单的WebSocket Demo,您可以根据自己的需求进行修改。希望能帮到您!如果您有任何问题,欢迎继续提问!
阅读全文