一。开启webSocket支持
@Configuration
public class AppConfig {
/**
* 开启webSocket支持
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
二定义webSocket给前端调用
/**
-
@author yys
/
@ServerEndpoint(value="/webSocket/{tentId}/{departId}/{userId}")
@Component
public class WebSocketServer {
private Session session;
public static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet();
private Long tentId;
private Long departId;
private Long userId;
/*- 确保多登都能收到消息的随机数
*/
private String suiJi;
@OnOpen
public void onOpen(Session session,
@PathParam(“tentId”)Long tentId,
@PathParam(“departId”)Long departId,
@PathParam(“userId”)Long userId) throws InterruptedException {
this.session = session;
this.tentId= tentId;
this.userId=userId;
this.departId=departId;
this.suiJi = LocalDateTime.now().format(DateTimeFormatter.ofPattern(“yyyyMMddHHmmss”));
webSockets.add(this);
System.out.println(“加入公司id: “+tentId+” 部门:”+departId+" 登陆人:"+userId);}
@OnClose
public void onClose(Session s) {
webSockets.remove(this);
System.out.println(“有公司离开”);
}
@OnMessage
public void onMessage(String msg) throws InterruptedException {
System.out.println("接受的消息: "+msg);
}
/**-
开放口子给服务器发送消息
-
此逻辑和消息存库,已读未读没关系,但消息查看后要把库里消息变为已读
-
msg里包含messageId等等
-
@param msg
*/
public static void send(String msg,Long tentId,Long departId,Long userId) {
webSockets.parallelStream().forEach(i->{
if(tentIdnull){
//群发
sendMessage(i.session,msg);
}else {
if(i.tentId.equals(tentId)){
if(departIdnull || i.departId.equals(departId)){if(userId ==null || i.userId.equals(userId)){ sendMessage(i.session,msg); } } } } });
}
public static void sendMessage(Session session,String msg){
try {
session.getBasicRemote().sendText(msg);
}catch (Exception e){
}
}
} - 确保多登都能收到消息的随机数
四提供测试用的静态页面
-->