WebSocket协议是一种建立在TCP连接基础上的全双工通信的协议。应用于即时通信等场景。
全双工通信:客户端和服务端可以同时进行双向通信。
添加gradle依赖:
compile'com.squareup.okhttp3:okhttp:3.6.0'
代码如下:
private String WEBSOCKETPATH="wss://xxx.xx.xx";
public WebSocket socket=null;
//创建WebSocket链接
OkHttpClient client =newOkHttpClient.Builder()
.retryOnConnectionFailure(true)//允许失败重试
.connectTimeout(8,TimeUnit.SECONDS)
.readTimeout(5,TimeUnit.SECONDS)
.writeTimeout(5,TimeUnit.SECONDS)
.build();
Request request =newRequest.Builder().url(WEBSOCKETPATH).build();
client.newWebSocket(request, new WebSocketListener() {
@Override
public void onOpen(WebSocket webSocket,Response response) {
socket=webSocket;
}
@Override
public void onMessage(WebSocket webSocket,String text) {
runOnUiThread(newRunnable() {
@Override
public void run() {
}
});
}
@Override
public void onMessage(WebSocket webSocket,ByteString bytes) {
}
@Override
public void onClosing(WebSocket webSocket, intcode,String reason) {
webSocket.close(1000, null);
}
@Override
public void onClosed(WebSocket webSocket, intcode,String reason) {
super.onClosed(webSocket,code,reason);
}
@Override
public void onFailure(WebSocket webSocket,Throwable t,Response response) {
if(t instanceof SocketTimeoutException){//连接超时
Log.i("erro",t.getMessage());
}else if(t instanceof UnknownHostException){//服务器主机未找到
Log.i("erro",t.getMessage());
}else{//其他错误
t.printStackTrace();
}
webSocket.close(1000, null);
}
});
client.dispatcher().executorService().shutdown();
更多:
http://www.open-open.com/lib/view/open1476778263175.html