package com.example.utils.SockJs;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
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 java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
/*
org.java-websocket
Java-WebSocket
1.5.2
*/
/**
* 请求工具
*/
public class SockJsTool extends StompSessionHandlerAdapter {
/**
* 请求地址
*/
private String url;
/**
* 请求 token
*/
private String token;
/**
*
*/
private StompSession session;
public SockJsTool(String url, String token) {
this.url = url;
this.token = token;
this.httpConnect();
}
public SockJsTool(String url) {
this.url = url;
this.httpConnect();
}
public SockJsTool() {
}
public StompSession getSession() {
return session;
}
/**
* http 链接websocket
*/
public void httpConnect(){
//判断是否已连接
if(session == null||!session.isConnected()){
System.out.println("当前处于断开状态,尝试链接");
List 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);
stompHeaders.set("user","1");
ListenableFuture future = webSocketStompClient.connect(url, webSocketHttpHeaders, stompHeaders, new SockJsTool());
try {
this.session = future.get();
this.session.setAutoReceipt(true);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
}