SpringBoot创建websocket
创建WebSocket服务
导入依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
创建配置类
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
创建 websocket
java
@Slf4j
@Component
@ServerEndpoint("/ws")
public class MyWebSocket {
private static final ConcurrentHashMap<String, Session> userWebMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session) {
userWebMap.put(session.getId(), session);
System.out.println("onOpen");
}
@OnMessage
public void onMessage(String message) {
System.out.println("onMessage");
}
@OnClose
public void onClose(Session session) {
System.out.println("onClose");
userWebMap.remove(session.getId());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("onError");
userWebMap.remove(session.getId());
}
public static void sendMessageToAll(String message) {
userWebMap.forEach((id, session) -> session.getAsyncRemote().sendText("hello " + id + " " + message));
}
}
启动服务前端连接尝试
js
let ws = new WebSocket("ws://localhost:8080/ws")
ws.onopen = function () {
ws.send("hello")
console.log(111)
}
ws.onmessage = function (event) {
console.log(event)
}
ws.onerror = function (event) {
console.log(event)
}