android io.socket如何拦截所有监听事件实现和服务器端anything一样的事件
短信预约 -IT技能 免费直播动态提醒
重写OkHttpClient
作者:晓果博客
class MyOkHttpClient extends OkHttpClient {
@Override
public WebSocket newWebSocket(Request request, final WebSocketListener listener) {
WebSocketListener webSocketListener = new WebSocketListener() {
public void onOpen(WebSocket webSocket, Response response) {
listener.onOpen(webSocket, response);
}
public void onMessage(WebSocket webSocket, String text) {
int index = text.indexOf("[\"transinfo");
if (!TextUtils.isEmpty(text) && index 0) {
try {
String be = text.substring(0, text.indexOf("["));
String af = text.substring(text.indexOf("["));
String bb = be + "[\"test\",{\"data\":[" + af + "]}]";
listener.onMessage(webSocket, bb);
} catch (Exception e) {
e.printStackTrace();
}
} else {
listener.onMessage(webSocket, text);
}
}
public void onMessage(WebSocket webSocket, ByteString bytes) {
listener.onMessage(webSocket, bytes);
Log.d("TTTT", "onMessage bytes==>" + bytes.toString());
}
public void onClosing(WebSocket webSocket, int code, String reason) {
listener.onClosing(webSocket, code, reason);
}
public void onClosed(WebSocket webSocket, int code, String reason) {
listener.onClosed(webSocket, code, reason);
}
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
listener.onFailure(webSocket, t, response);
}
};
RealWebSocket webSocket = new RealWebSocket(request, webSocketListener, new Random(), pingIntervalMillis());
webSocket.connect(this);
return webSocket;
}
}
这里将所有以transinfo开头的事件全部转化为test事件。
配置 io.socket的webSocketFactory
IO.Options opts = new IO.Options();
// OkHttpClient webSocketFactory = new OkHttpClient.Builder()
// .proxy(Proxy.NO_PROXY)
// .build();
// OkHttpClient callFactory = new OkHttpClient.Builder()
// .proxy(Proxy.NO_PROXY)
// .build();
// opts.webSocketFactory = webSocketFactory;
// opts.callFactory = callFactory;
//失败重试次数
// opts.reconnectionAttempts = 10;
//失败重连的时间间隔
// opts.reconnectionDelay = 1000;
//连接超时时间(ms)
// opts.timeout = 500;
MyOkHttpClient aa = new MyOkHttpClient();
aa.newBuilder().proxy(Proxy.NO_PROXY);
opts.webSocketFactory = aa;
opts.query = query;
// opts.forceNew = true;
opts.transports = new String[]{"websocket"};
mSocket = IO.socket(url, opts);
mSocket.off();
listenSignalEvents();
mSocket.connect();
设置监听
mSocket.on("test", new Socket.Listener() {
@Override
public void call(Object... args) {
LogUtil.e("aaaaaaa");
LogUtil.e(args[0].toString());
}
});
接收服务器端数据
作者:晓果博客
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341