盗代码

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

一、maven导入依赖

<!-- websocket -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

二、启动类进行调整

@SpringBootApplication
@EnableAsync
public class EngoalBiApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(EngoalBiApplication.class, args);
        //解决WebSocket不能注入的问题
        WebSocket.setAppcontext(configurableApplicationContext);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

三、添加websocket配置类

@ServerEndpoint("/websocket/{pageCode}")
@Component
public class WebSocket {

    private static final String loggerName = WebSocket.class.getName();
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    public static Map<String, List<Session>> electricSocketMap = new ConcurrentHashMap<String, List<Session>>();

    //关键代码,设置一个静态上下文属性appcontext
    private static ApplicationContext appcontext;
    public static void setAppcontext(ApplicationContext appcontext) {
        WebSocket.appcontext = appcontext;
    }
    public static ApplicationContext getAppcontext() {
        return appcontext;
    }
    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam("pageCode") String pageCode, Session session) throws IOException {
        List<Session> sessions = electricSocketMap.get(pageCode);
        if (null == sessions) {
            List<Session> sessionList = new ArrayList<>();
            sessionList.add(session);
            electricSocketMap.put(pageCode, sessionList);
        } else {
            sessions.add(session);
            //applicationContext使用
            InsideJobtimeService insideJobtimeService = appcontext.getBean(InsideJobtimeService.class);
            SysTableStatusDao sysTableStatusDao = appcontext.getBean(SysTableStatusDao.class);
            Map<String, Object> map = insideJobtimeService.GetInsideJobtimeMap();
            while (1==1){
                Integer status = sysTableStatusDao.GetTableStatus("tb_inside_jobTime");
                if(status == 0 ) {
                    sysTableStatusDao.UpdateTableStatus("tb_inside_jobTime");
                    map = insideJobtimeService.GetInsideJobtimeMap();
                }
                session.getBasicRemote().sendText(JSON.toJSONString(map));
            }
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("pageCode") String pageCode, Session session) {
        if (electricSocketMap.containsKey(pageCode)) {
            electricSocketMap.get(pageCode).remove(session);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {

        try {
//            session.getBasicRemote().sendText("这是推送测试数据!您刚发送的消息是:"+message);
            for (List<Session> s : electricSocketMap.values()) {
                for (int i = 0; i < s.size(); i++) {
                    s.get(i).getBasicRemote().sendText(message);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        ;
    }
}

四、前台代码的编写

if ('WebSocket' in window) {
                    websocket = new WebSocket("ws://192.168.31.116:12124/websocket/1");
                } else {
                    alert("您的浏览器不支持websocket");
                }
                websocket.onerror = function() {
                    setMessageInHtml("send error!");
                }
                websocket.onopen = function() {
                    setMessageInHtml("连接建立成功!")
                }
                websocket.onmessage = function(event) {
                    setMessageInHtml(event.data);
                }
                websocket.onclose = function() {
                    setMessageInHtml("closed websocket!")
                }
                window.onbeforeunload = function() {
                    clos();
                }

                function setMessageInHtml(param) {
                    //获取返回值后执行的代码段
                }
                //主动发送参数给后台
                function send() {
                    var msg = 'aa';
                    websocket.send(msg);
                }

                function clos() {
                    websocket.close(3000, "强制关闭");
                }                                

  

 

posted on 2021-06-16 11:09    阅读(160)  评论(0)    收藏  举报