implementation 'com.dhh:websocket:2.1.2'
//init config 在使用RxWebSocket之前设置即可,推荐在application里初始化
Config config = new Config.Builder()
.setShowLog(true) //show log
.setClient(yourClient) //if you want to set your okhttpClient
.setShowLog(true, "your logTag")
.setReconnectInterval(2, TimeUnit.SECONDS) //set reconnect interval
.setSSLSocketFactory(yourSSlSocketFactory, yourX509TrustManager) // wss support
.build();
RxWebSocket.setConfig(config);
Config config = new Config.Builder()
.setClient(new OkHttpClient.Builder()
.pingInterval(3, TimeUnit.SECONDS) // 设置心跳间隔,这个是3秒检测一次
.build()) //if you want to set your okhttpClient
.build();
RxWebSocket.get("url")
.subscribe(new WebSocketSubscriber() {
@Override
protected void onMessage(@NonNull String text) {
}
});
RxWebSocket.get("your url")
//RxLifecycle : https://github.com/dhhAndroid/RxLifecycle
.compose(RxLifecycle.with(this).<WebSocketInfo>bindToLifecycle())
.subscribe(new WebSocketSubscriber() {
@Override
public void onOpen(@NonNull WebSocket webSocket) {
Log.d("MainActivity", "onOpen1:");
}
@Override
public void onMessage(@NonNull String text) {
Log.d("MainActivity", "返回数据:" + text);
}
@Override
public void onMessage(@NonNull ByteString byteString) {
}
@Override
protected void onReconnect() {
Log.d("MainActivity", "重连:");
}
@Override
protected void onClose() {
Log.d("MainActivity", "onClose:");
}
});
/**
*
*如果你想将String类型的text解析成具体的实体类,比如{@link List<String>},
* 请使用 {@link WebSocketSubscriber2},仅需要将泛型传入即可
*/
RxWebSocket.get("your url")
.compose(RxLifecycle.with(this).<WebSocketInfo>bindToLifecycle())
.subscribe(new WebSocketSubscriber2<List<String>>() {
@Override
protected void onMessage(List<String> strings) {
}
});
//用WebSocket的引用直接发
mWebSocket.send("hello word");
//url 对应的WebSocket 必须打开,否则报错
RxWebSocket.send(url, "hello");
RxWebSocket.send(url, ByteString.EMPTY);
//异步发送,若WebSocket已经打开,直接发送,若没有打开,打开一个WebSocket发送完数据,直接关闭.
RxWebSocket.asyncSend(url, "hello");
RxWebSocket.asyncSend(url, ByteString.EMPTY);
RxJava的注销方式,就可以取消订阅.
Subscription subscription = RxWebSocket.get("ws://sdfs").subscribe();
//注销
if(subscription!=null&&!subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.