websocket的stomp客户端,包含自动重连功能

转载自: https://blog.csdn.net/k3108001263/article/details/88088882

javascript版本

<meta charset="UTF-8">
<script type="text/javascript" src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<html>
<body>
<script>
var stomp = null;//定义全局变量,表明一个session
function connect(){    //定义链接函数
    if(stomp == null || !stomp.connected){    
        //var url = 'http://132.122.237.68:8164/websocket';
        var url = 'http://localhost:8164/websocket';
        //var url = '/websocket';
        var headers={
            "token":"admin_token"    
        };
        var sockJS = new SockJS(url);
        stomp = Stomp.over(sockJS);
        stomp.heartbeat.outgoing = 20000; //若使用STOMP 1.1 版本,默认开启了心跳检测机制(默认值都是10000ms)
        stomp.heartbeat.incoming = 0; //客户端不从服务端接收心跳包
        console.log("当前处于断开状态,尝试链接");
        stomp.connect(headers, connectCallback ,errorCallback );
    }else{
        console.log("当前处于链接状态");
    }
}

function connectCallback (frame) {  //链接成功时的回调函数
    stomp.subscribe("/topic/wechat/message/receiveText/12345", function (result) {  
        var content = result.body;
        console.log("接收订阅消息="   +content);
    }, {});       
}
function errorCallback(){//链接失败时的回调函数,此函数从新调用链接方法,造成循环,直到链接成功    
    connect();    
}
connect();//创建链接
</script>
</body>
</html>

java版本

package com.github.qq275860560.wechat.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangyuanlin@163.com
 */
@Slf4j
public class ReceiveTextStompClient {
    private static String url = "http://132.122.237.244:8244/websocket";
    private static String token = "freeswitch_token";
    private static StompSession stompSession;// 定义全局变量,表明一个session

    public static void connect() {// 定义链接函数
        if (stompSession == null || !stompSession.isConnected()) {
            log.info("当前处于断开状态,尝试链接");
            List<Transport> transports = new ArrayList<>();
            transports.add(new WebSocketTransport(new StandardWebSocketClient()));
            SockJsClient sockJsClient = new SockJsClient(transports);
            WebSocketStompClient webSocketStompClient = new WebSocketStompClient(sockJsClient);
            webSocketStompClient.setMessageConverter(new StringMessageConverter());
            webSocketStompClient.setDefaultHeartbeat(new long[] { 20000, 0 });
            ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.afterPropertiesSet();
            webSocketStompClient.setTaskScheduler(taskScheduler);
            WebSocketHttpHeaders webSocketHttpHeaders = null;
            StompHeaders stompHeaders = new StompHeaders();
            stompHeaders.add("token", token);
            StompSessionHandler receiveTextStompSessionHandler = new ReceiveTextStompSessionHandler();
            try {
                ListenableFuture<StompSession> future = webSocketStompClient.connect(url, webSocketHttpHeaders,
                        stompHeaders, receiveTextStompSessionHandler);
                stompSession = future.get();
                stompSession.setAutoReceipt(true);
                stompSession.subscribe("/topic/wechat/message/receiveText/12345", receiveTextStompSessionHandler);
                // stompSession.send("/app/wechat/message/sendText", jsonString.getBytes());
            } catch (Exception e) {

            }
        } else {
            log.info("当前处于链接状态");
        }

    }

    public static void main(String[] args) {// 创建链接
        while (stompSession == null || !stompSession.isConnected()) {
            connect();// 链接服务器
            try {
                Thread.sleep(3000);// 链接服务器失败的处理 3秒后从新链接
            } catch (Exception e1) {
            }
        }
        new Scanner(System.in).nextLine();
    }

}
package com.github.qq275860560.wechat.client;

import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;

import lombok.extern.slf4j.Slf4j;

/**
 * @author jiangyuanlin@163.com
 */
@Slf4j
public class ReceiveTextStompSessionHandler extends StompSessionHandlerAdapter {
    @Override
    public void handleFrame(StompHeaders headers, Object payload) {
        log.info("接收订阅消息=" + (String) payload);
    }

    @Override
    public void handleTransportError(StompSession stompSession, Throwable exception) {
        log.error("",exception);
        //super.handleTransportError(stompSession, exception);
        try {
            Thread.sleep(3000);
            ReceiveTextStompClient.connect();
        } catch (InterruptedException e) {
            log.error("",e);
        }
    }
}

 

posted @ 2021-03-03 15:51  fy_qxl  阅读(2248)  评论(0编辑  收藏  举报