IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Websocket + Scheduled 服务的实现 - JAVA -> 正文阅读

[网络协议]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

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-21 12:46:40  更:2021-10-21 12:48:02 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年7日历 -2024/7/3 11:46:16-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码