Spring 集成WebSocket实现消息实时传输到前端

本文主要解决的是Spring WebSocket无法注入,或者是声明的web socket前端无法获取到,WebSocket

因此本文使用的是Java WebSocket 结合Spring的配置来进行消息传输

后端

@ServerEndpoint(value="/websocketDemo/press.do",configurator = SpringConfigurator.class)
public class WebsocketDemo {
    private static final Set<WebsocketDemo> connections = new CopyOnWriteArraySet<>();

    private String nickname;
    private Session session;




    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        return super.hashCode();
    }


    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        return super.equals(obj);
    }


    @OnOpen
    public void start(Session session) {
        this.session = session;
        connections.add(this);
        String msg = "NAME" + "\t" + nickname;
        try {
            this.session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("连接数量:"+connections.size());
    }


    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format("* %s %s",
                nickname, "has disconnected.");
        broadcast(message);
        System.out.println(nickname+" 关闭");
    }


    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                nickname, HTMLFilter.filter(message.toString()));
        System.out.println("filteredMessage:"+filteredMessage);
        broadcast(message);
    }




    @OnError
    public void onError(Throwable t) throws Throwable {
    }


    public void broadcast(String msg) {
        for(WebsocketDemo user:connections){
                try {
                    user.session.getBasicRemote().sendText(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }   

    }

直接调用broadcast进行消息广播

前端

前端接收广播消息

                      var host =window.location.host;
                      if ('WebSocket' in window) {
                          websocket = new WebSocket("ws://localhost:8080/web/websocketDemo/press.do");
                      } else if ('MozWebSocket' in window) {
                          websocket = new MozWebSocket("ws://localhost:8080/web/websocketDemo/press.do");
                      } else {
                          websocket = new SockJS("http://localhost:8080/web/websocketDemo/press.do");
                      }
                      websocket.onopen = function (evnt) {
                          console.log("开启socket");
                      };
                      websocket.onmessage = function (evnt) {
                          //确认按键 od
                          if(evnt.data == "0d"){
                                block();
                            }
                          else if(evnt.data == "1b"){
                              //取消按键 1b
                              console.log("cancel");

                          }else if(evnt.data == "2a"){
                              console.log("*");
                              //正常数字 2a
                          }else if(evnt.data =="08"){
                              console.log("delete");
                              //更正数字 08
                          }else if(evnt.data =="80"){
                              //超时数字 80  超时之后再次调用启动加密接口即可重新输入密码
                              eject();
                          }
                      };
                      websocket.onerror = function (evnt) {
                          console.log("发生错误");
                      };
                      websocket.onclose = function (evnt) {
                          console.log("关闭");
                      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值