当前位置:   article > 正文

Autoxjs 实践-Spring Boot 集成 WebSocket_autojs websocket

autojs 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>
  • 1
  • 2
  • 3
  • 4

WebSocket配置类

@Configuration
public class WebSocketConfig{

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

消息核心类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;
    		}
    	}
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

总结

资源仅为学习参考!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/880544
推荐阅读
相关标签
  

闽ICP备14008679号