1.maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.配置类
/**
* 开启WebSocket
* WebScoket配置
* 通过这个配置 spring boot 才能去扫描后面的关于 websocket 的注解
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3.demo
@Component
@Slf4j
//访问路径 ws://localhost:8081/websocketdemo?userId=1
@ServerEndpoint(value = "/websocketdemo")
public class Demo {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static final AtomicInteger currentOnlineNumber = new AtomicInteger();
//消息存储
private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();
@OnOpen //收到socket请求触发
public void onOpen(Session session) throws IOException {
//获取传递的参数userId
String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
currentOnlineNumber.incrementAndGet(); //当前在线数量+1
sessionPool.put(userId, session);//session存储
log.info("用户:___" + userId + "___成功连接,当前在线用户___" + currentOnlineNumber);
}
@OnClose//关闭socket请求触发
public void onClose(Session session) {
//获取传递的参数userId
String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
currentOnlineNumber.decrementAndGet();//当前在线数量-1
sessionPool.remove(userId);//session删除
log.info("用户:___" + userId + "___断开连接,当前在线用户在线人数___" + currentOnlineNumber);
}
@OnMessage//收到socket请求触发(用于心跳检测)
public void OnMessage(Session session, String message) throws IOException {
//获取传递的参数userId
String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
log.info("收到___" + userId + "___推送消息" + message);
if (ObjectUtil.isEmpty(message) && message.contains("ping")) {
sessionPool.get(userId).getBasicRemote().sendText(JSON.toJSONString("pong"));
}
//推送消息给用户
HashMap<String, Object> mapq = new HashMap<>();
mapq.put("1", "2");
mapq.put("3 ", "4");
this.onMessagePush(userId, mapq);
}
/**
* 给指定用户推送消息
*
* @param userId
* @throws IOException
*/
public <T> void onMessagePush(String userId, T t) throws IOException {
log.info(t.toString());
sessionPool.get(userId).getBasicRemote().sendText(JSON.toJSONString("notice|" + t));
}
}