完整demo,webSocket实现浏览器消息推送系统

一。开启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(departId
      null || 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){
    }
    }
    }

四提供测试用的静态页面

-->
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值