Android Okhttp 之WebSocket简单使用
作者:互联网
android实现一个聊天功能,okhttp内置的websocket蛮好用的,简单介绍其使用方式
1.项目用的是retrofit2自带okhttp,没有的话添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
2.重要的网络权限不能少
<uses-permission android:name="android.permission.INTERNET"/>
3.某个activity中初始化
OkHttpClient client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)//允许失败重试
.readTimeout(5, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(5, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(5, TimeUnit.SECONDS)//设置连接超时时间
.build();
String url = ws://web.xxx.xxx.com:xxx//服务器获取的url
Request request = new Request.Builder().url(url).build();
WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {//主要的几个方法(在子线程中回调,刷新UI记得使用Handler)
@Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
//连接成功
}
@Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
//接收服务器消息 text
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
//如果服务器传递的是byte类型的
String msg = bytes.utf8();
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
super.onFailure(webSocket, t, response);
//连接失败调用 异常信息t.getMessage()
}
});
client.dispatcher().executorService().shutdown();//内存不足时释放
}
4.需要将信息传递给服务器
webSocket.send("发送的消息")
原文链接:https://blog.csdn.net/m0_38020167/article/details/82151852
标签:webSocket,void,onMessage,Okhttp,WebSocket,Android,super,public 来源: https://blog.csdn.net/yangjunjin/article/details/118788599