1.先引用模板和websocket依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--添加websocket依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>
2.添加webSocketConfig配置类
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 在启动类中添加注解@EnableScheduling
@SpringBootApplication
@EnableScheduling//开启定时任务支持
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4.添加webSocketServer服务端类
package com.example.demo.controller;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/{userno}")
@Component
public class Websocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, Websocket> webSocketSet = new ConcurrentHashMap<String, Websocket>();
//也是用来存放WebSocket对象 用来定时任务用
private static HashMap<String, String> hashMap= new HashMap<String, String>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//当前发消息的人员编号
private String userno = "";
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session session, EndpointConfig config) {
System.out.println(param);
userno = param;//接收到发送消息的人员编号
this.session = session;
/**
* hashMa