这是Android WebSocket客户端监听的使用
1、安卓没有适配Stom协议的WebSocket监听,所以只能自己进行Okhttp封装
2、以下是借助Okhttp和Stomp进行WebSocket长链接监听
1. 依赖引入
// implementation 'org.java-websocket:Java-WebSocket:1.3.6'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
implementation 'com.android.support:recyclerview-v7:28.0.0'
// RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.5'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
2. 代码实现
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private SimpleAdapter mAdapter;
private List<String> mDataSet = new ArrayList<>();
private StompClient mStompClient;
private Disposable mRestPingDisposable;
private final SimpleDateFormat mTimeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
private RecyclerView mRecyclerView;
private Gson mGson = new GsonBuilder().create();
private CompositeDisposable compositeDisposable;
@Override
protected void onCreate(Bundle savedInstanceState) {
mStompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, "ws://" + 主机地址
+ ":" + 端口号 + "/example-endpoint/websocket");
}
public void disconnectStomp(View view) {
mStompClient.disconnect();
}
public static final String LOGIN = "login";
public static final String PASSCODE = "passcode";
public void connectStomp(View view) {
List<StompHeader> headers = new ArrayList<>();
headers.add(new StompHeader(LOGIN, "guest"));
headers.add(new StompHeader(PASSCODE, "guest"));
mStompClient.withClientHeartbeat(1000).withServerHeartbeat(1000);
Disposable dispLifecycle = mStompClient.lifecycle()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(lifecycleEvent -> {
switch (lifecycleEvent.getType()) {
case OPENED:
toast("Stomp connection opened");
break;
case ERROR:
Log.e(TAG, "Stomp connection error", lifecycleEvent.getException());
toast("Stomp connection error");
break;
case CLOSED:
toast("Stomp connection closed");
resetSubscriptions();
break;
case FAILED_SERVER_HEARTBEAT:
toast("Stomp failed server heartbeat");
break;
}
});
compositeDisposable.add(dispLifecycle);
Disposable dispTopic = mStompClient.topic("/topic/greetings")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(topicMessage -> {
Log.d(TAG, "Received " + topicMessage.getPayload());
addItem(mGson.fromJson(topicMessage.getPayload(), EchoModel.class));
}, throwable -> {
Log.e(TAG, "Error on subscribe topic", throwable);
});
compositeDisposable.add(dispTopic);
mStompClient.connect(headers);
}
@Override
protected void onDestroy() {
mStompClient.disconnect();
if (mRestPingDisposable != null) mRestPingDisposable.dispose();
if (compositeDisposable != null) compositeDisposable.dispose();
super.onDestroy();
}
}
附件。
|