Websocket + Scheduled 服务的实现 - JAVA

1、参考链接

https://www.bilibili.com/video/BV1r54y1D72U?from=search&seid=2193943377005329491&spm_id_from=333.337.0.0

2、注解的方式

服务端代码实现=

package com.zhangz.innokproject.config.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import javax.websocket.server.ServerEndpointConfig;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
//GetHttpInfosConfigurator 自定义实现可以从httprequest获取相关信息
//value = "/websocket/{client}" 可以用这种URL方式传参,@PathParam("client") String client获取url后面的参数
@ServerEndpoint(value = "/websocket",configurator = GetHttpInfosConfigurator.class)
public class DemoForWebsocket {
	//保存所有与服务端建立连接的客户端信息
    private static Map<String,DemoForWebsocket> onlineClients = new ConcurrentHashMap<>();

    public static Map<String, DemoForWebsocket> getOnlineClients() {
        return onlineClients;
    }

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
	//存放每个客户端的名称
    private String client;
    /**
     * 连接建立成功调用的方法 @PathParam("machine") String client,
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     * @throws Exception
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config) throws Exception{
        this.session = session;
        //String machine = (String) config.getUserProperties().get("machine");
      
    }

    /**
     * 连接关闭调用的方法 @PathParam("machine") String client
     * @throws Exception
     */
    @OnClose
    public void onClose() throws Exception{
        //从map中删除
        session.close();
        onlineClients.remove(client);
        log.info("离线客户端:"+client+"\n在线客户端:"+onlineClients.toString());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        try {
            HashMap<String,String> map = JSONObject.parseObject(message, HashMap.class);
            //取出客户端信息并保存当地
            String machine = map.get("machine");
            String type = map.get("type");
            log.info("==========="+type+"==========="+machine);
            this.client = type+"-"+machine;
            onlineClients.put(this.client,this);
            log.info("在线客户端:"+onlineClients.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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


    /**
     * 发送消息方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

}

3、配置websocket

package com.zhangz.innokproject.config.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebsocketConfig {
    @Bean
    //ServerEndpointExporter主要作用是扫描@ServerEndpoint注解、
    public ServerEndpointExporter getEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

##4、 EndpointConfig配置类

package com.zhangz.innokproject.config.websocket;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

public class GetHttpInfosConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> parameterMap = request.getParameterMap();
        sec.getUserProperties().putAll(parameterMap);
        super.modifyHandshake(sec, request, response);
    }
}

5、定时推送客户端

package com.hlxd.innokproject.config.websocket;

import com.alibaba.fastjson.JSONObject;
import com.hlxd.innokproject.bean.MachineQuotoGroup;
import com.hlxd.innokproject.service.QuotoMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

@Service
@EnableScheduling
@Slf4j
public class WebSocketService {

    @Resource
    private QuotoMonitorService quotoMonitorService;


    @Scheduled(cron = "0 */1 * * * ?")
    public void getMachineInfo(){
        MachineQuotoGroup machineQuotoGroup = null;
        try {
            Map<String, DemoForWebsocket> onlineClients = DemoForWebsocket.getOnlineClients();
            log.info("====onlineClients===="+onlineClients.size());
            if (onlineClients.isEmpty()) return;
            Set<String> set = onlineClients.keySet();
            for (String key : set){
            	//machineQuotoGroup  =   实现自己的逻辑往客户端推 
                onlineClients.get(key).sendMessage(JSONObject.toJSONString(machineQuotoGroup));
            }
        } catch (Exception e) {
            log.info("====websocket=====异常=====");
            e.printStackTrace();
        }
    }
}

6、websocket在线工具

http://oktools.net/websocket

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值