第一步:引入依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步设置配置类:
// 需要注入Bean的话必须声明为配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
第三步实体类:
//定义的endpoint类
@Component
@ServerEndpoint(value = "/chat")//前端中写的访问websocket的路径
public class MyWebSocketServer {
// 因为可能有多个客户端所以这里需要保证线程安全,这个是存储每个客户端的,每个客户端都是一个session
static Map<String,Session> sessionMap = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
* @throws Exception
*/
// 建立连接时执行的操作
@OnOpen
public void onOpen(Session session){ // 每个websocket连接对于服务端来说都是一个Session
System.out.println("----------------------------------------");
sessionMap.put(session.getId(),session);
System.out.println("websocket is open");
System.out.println(session);
}
/**
* 收到客户端消息时执行的操作
* @param text 接受到客户端的消息
* @return 返回给客户端的消息
*/
@OnMessage
public String onMessage(String text){
System.out.println("收到一条新消息: " + text);
return "收到 !";
}
// 连接关闭时执行的操作
@OnClose
public void onClose(Session session){
System.out.println("websocket is close1111111111");
}
@Scheduled(fixedRate = 2000) // 每隔2s执行一次
public void sendMessage() throws IOException {
System.out.println("长连接");
System.out.println(sessionMap.keySet());
for(String key: sessionMap.keySet()){ // 给所有客户端发送消息
sessionMap.get(key).getBasicRemote().sendText("beat");
}
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
}
注意上面的代码如果想要给客户端返回信息需要在启动类上加上注解
@EnableScheduling //这里在使用websocket时一定要加上
Scheduled(fixedRate = 2000) // 每隔2s执行一次 public void sendMessage() throws IOException { System.out.println("长连接"); System.out.println(sessionMap.keySet()); for(String key: sessionMap.keySet()){ // 给所有客户端发送消息 sessionMap.get(key).getBasicRemote().sendText("beat"); } } //就是执行这段返回信息的代码
前端:




















