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) {
// 连接websocket服务端
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);
// 订阅服务提供的topic
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();
}
}