Android 与服务器建立单向链接的SSE通讯机制
前段时间公司有个项目需求,需要与后台服务器保持一个单向的长链接,也就是说只需要服务器向客户端发送指令,客户端做出相应操作就可以了,并不需要客户端向服务端发送什么请求。
网上找了很多资料,发现服务端用的SSE建立单向链接大多数是用到web端的,关于Android端的资料很少,经过一番探查,总算成功建立连接,以下代码为记录所用,觉得无用请划走即可。
1、必须确保我们的项目集成了相关依赖,这个链接机制肯定是基于okhttp的撒
implementation 'com.squareup.okhttp3:okhttp:4.11.0'
implementation 'com.squareup.okhttp3:okhttp-sse:4.11.0'
2、这里我是自己写了一个工具类,需要的时候直接调用就可以了,虽然通篇就只调用了一次
直接贴出全部代码了
public class SSEClient {
private static SSEClient mInstance;
private SSEClient() {
}
public static synchronized SSEClient getInstance() {
if (mInstance == null) {
mInstance = new SSEClient();
}
return mInstance;
}
private EventSourceListener eventSourceListener;
//3
public void testOkhttpSSE(String userId) {
String url = baseUrl + userId;
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.DAYS)
.readTimeout(1, TimeUnit.DAYS)
.build();
Request request = new Request.Builder().url(url).build();
EventSource.Factory factory = EventSources.createFactory(okHttpClient);
eventSourceListener = new EventSourceListener() {
/
* {@inheritDoc}
*/
@Override
public void onOpen(final EventSource eventSource, final Response response) {
LogUtil.e("建立sse连接...","建立sse连接...");
}
/
* {@inheritDoc}
*/
@Override
public void onEvent(final EventSource eventSource, final String id, final String type, final String data) {
LogUtil.e("建立sse连接成功","建立sse连接成功" + data);
if (mSseConnectSucccesListener != null){
mSseConnectSucccesListener.getData(data);
}
}
/
* {@inheritDoc}
*/
@Override
public void onClosed(final EventSource eventSource) {
LogUtil.e("建立sse连接关闭","建立sse连接关闭");
//连接失败尝试重新连接
if (request != null && eventSourceListener != null){
LogUtil.e("SSEClient","连接异常,正在尝试重新连接...");
factory.newEventSource(request,eventSourceListener);
}else {
ToastUtils.showShort("连接异常,请稍后重试");
}
}
/
* {@inheritDoc}
*/
@Override
public void onFailure(final EventSource eventSource, final Throwable t, final Response response) {
// LogUtil.e("使用事件源时出现异常","连接服务端时出现异常-----" + response.message());
//连接失败尝试重新连接
if (request != null && eventSourceListener != null){
LogUtil.e("SSEClient","连接异常,正在尝试重新连接...");
factory.newEventSource(request,eventSourceListener);
}else {
ToastUtils.showShort("连接异常,请稍后重试");
}
}
};
//创建事件
factory.newEventSource(request, eventSourceListener);
//由于springboot test异步的,加下面代码卡住同步
// CountDownLatch countDownLatch = new CountDownLatch(1);
// try {
// countDownLatch.await();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
//建立监听回调
private SSEConnectSucccesListener mSseConnectSucccesListener;
public void getSSEMessage(SSEConnectSucccesListener sseConnectSucccesListener){
mSseConnectSucccesListener = sseConnectSucccesListener;
}
public interface SSEConnectSucccesListener{
void getData(String data);
}
上面这段代码写的是一个单例模式,还是那句话,通篇只使用一次。里面的baseUrl是自己的服务器地址,copy的时候自己添加就可以了,下面的监听会把你需要的数据传递出去。