Autoxjs 实践-Spring Boot 集成 WebSocket

概述

最近弄了福袋工具,由于工具运行中,不好查看福袋结果,所以我想将福袋工具运行数据返回到后台,做数据统计、之后工具会越来越多,就弄了个后台,方便管理。

实现效果

在这里插入图片描述

在这里插入图片描述

WebSocket?

websocket是一种在单个TCP连接上进行全双工通讯的协议,websocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,在websocket中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

简单来说:WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

Autoxjs + Springboot + Websocket通用版

集成分为三步:添加依赖、增加配置类和消息核心类、Autoxjs集成。

maven 添加依赖

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

WebSocket配置类

@Configuration
public class WebSocketConfig{

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

}

消息核心类WebSocketServer

@ServerEndpoint("/websocket/{adminId}")
@Component
public class WebSocketMessage{
	/** 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 */
    private static int onlineCount = 0;
     
    /** concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 */
    private static CopyOnWriteArraySet<WebSocketMessage> webSocketSet = new CopyOnWriteArraySet<WebSocketMessage>();
     
    /** 与某个客户端的连接会话,需要通过它来给客户端发送数据 */
    private Session session;

    protected static final Logger logger = LoggerFactory.getLogger(WebSocketMessage.class);
    
    /** 用户ID*/
    private String adminId;

    /**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("adminId") String adminId) throws IOException{
    	//重复标识
		//boolean isFlay = true;
		for(WebSocketMessage item: webSocketSet){
			if(adminId.equals(item.adminId)){
				item.onClose();
				//isFlay = false;
				//break;
			}
		}
		
		this.session = session;
	    this.adminId = adminId;
	    webSocketSet.add(this);     //加入set中
		addOnlineCount();           //在线数加1
	    logger.info("有新连接加入!当前在线人数为" + getOnlineCount() + "用户id:"+adminId);
    }
     
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1    
        logger.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
     
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	logger.info("来自客户端的消息:" + message);
    }
     
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
    	logger.info("发生错误:"+error.getMessage());
        error.printStackTrace();
    }
     
    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
    	this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }
 
    /**
     * 
     * @Description 获取在线人数
     * @Date 2019年8月6日 下午2:29:37
     * @Author Jly
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    /**
     * 
     * @Description 添加在线人数
     * @Date 2019年8月6日 下午2:30:01
     * @Author Jly
     */
    public static synchronized void addOnlineCount() {
    	WebSocketMessage.onlineCount++;
    }
     
    /**
     * 
     * @Description 减少在线人数
     * @Date 2019年8月6日 下午2:30:18
     * @Author Jly
     */
    public static synchronized void subOnlineCount() {
    	WebSocketMessage.onlineCount--;
    }
    
    /**
     * 测试页面接受信息
     * @param adminId
     * @param message
     */
    public static void sendDataMessage(String adminId, String message){
    	//群发消息
    	for(WebSocketMessage item: webSocketSet){             
    		try {
    			if(adminId.equals(item.adminId)){
    				item.sendMessage(message);
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    			continue;
    		}
    	}
    }
}

autoxJs webSocket

importPackage(Packages["okhttp3"]); //导入包
var globalWebsocket = null;
var client = new OkHttpClient.Builder().retryOnConnectionFailure(true).build();
// 需要根据自己改IP
var request = new 
Request.Builder().url("ws://192.168.0.91:8080/websocket/349075715535306752").build(); //vscode  插件的ip地址,
client.dispatcher().cancelAll();//清理一次
myListener = {
    onOpen: function (result, response) {
        console.log("连接成功");
        globalWebsocket = result
    },
    onMessage: function (webSocket, msg) { //msg可能是字符串,也可能是byte数组,取决于服务器送的内容
        print("msg");
        print(msg);
    },
    onClosing: function (webSocket, code, response) {
        print("正在关闭");
    },
    onClosed: function (webSocket, code, response) {
        print("已关闭");
    },
    onFailure: function (webSocket, t, response) {
        print("错误");
    }
}
function init() {
    webSocket = client.newWebSocket(request, new WebSocketListener(myListener)); //创建链接
}
function run() {
    try {
        if (globalWebsocket == null) {
            init();
            sleep(500)
        } else {
            var json = {};
            json.command = "PING"
            let success = globalWebsocket.send(JSON.stringify(json))
            if (!success) {
                console.log("发送失败")
            }
            sleep(1000)
        }

    } catch (e) {
        console.log(e)
    }
}
//发送心跳
threads.start(function () {
    setInterval(() => {
        run()
    }, 30 * 1000);
})

总结

资源仅为学习参考!!

相关推荐

  1. SpringBoot集成WebSocket

    2024-05-09 07:14:05       69 阅读
  2. springboot +vue 集成websocket

    2024-05-09 07:14:05       50 阅读
  3. springboot 集成websocket

    2024-05-09 07:14:05       58 阅读
  4. Springboot 集成websocket

    2024-05-09 07:14:05       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-09 07:14:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-09 07:14:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-09 07:14:05       87 阅读
  4. Python语言-面向对象

    2024-05-09 07:14:05       96 阅读

热门阅读

  1. 网络安全与信息安全

    2024-05-09 07:14:05       31 阅读
  2. 培养逻辑思考力的7大基本方法笔记

    2024-05-09 07:14:05       31 阅读
  3. Android调用C++函数

    2024-05-09 07:14:05       32 阅读
  4. WordPress如何判断当前页是否属于文章页或页面?

    2024-05-09 07:14:05       34 阅读
  5. python字典

    2024-05-09 07:14:05       33 阅读
  6. 个人消息22222222222222

    2024-05-09 07:14:05       29 阅读
  7. Linux(Ubuntu)安装CGAL(非root)

    2024-05-09 07:14:05       37 阅读
  8. element-ui select 下拉框做成下拉加载更多

    2024-05-09 07:14:05       37 阅读