步骤一:
注意,okhttp是3.5以后才添加对WebSocket的支持,以前都是提供了扩展库okhttp-ws,建议使用3.5以上版本。
在项目中添加
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
步骤二:
创建一个内部类,集成okhttp中抽象类WebSocketListener
private final class EchoWebSocketListener extends WebSocketListener {
@Override
public void onOpen(WebSocket webSocket, Response response) {
webSocket.send("hello world");
webSocket.send("welcome");
webSocket.send(ByteString.decodeHex("adef"));
// webSocket.close(1000, "再见");
}
@Override
public void onMessage(WebSocket webSocket, String text) {
// logger.e("onMessage","onMessage: " + text);
}
@Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
// logger.e("onMessage","onMessage: " + text); }
@Override
public void onClosing(WebSocket webSocket, int code, String reason) {
// webSocket.close(1000, null);
// logger.e("onClosing","onClosing: " + reason);
}
@Override
public void onClosed(WebSocket webSocket, int code, String reason) {
// logger.e("onClosed","onClosed: " + reason);
}
@Override
public void onFailure(WebSocket webSocket, Throwable t, Response response) {
// logger.e("onFailure","onFailure: " + t.toString+response.toString);
}
}
重写了WebSocketListener中的几个方法,这几个方法很好理解,是用来异步回调的,这里简单说一下:
onOpen当WebSocket和远程建立连接时回调;
两个onMessage就是接收到消息时回调,只是消息内容的类型不同;
onClosing是当远程端暗示没有数据交互时回调(即此时准备关闭,但连接还没有关闭,注意,此时并没有关闭);
onClosed就是当连接已经释放的时候被回调;
onFailure当然是失败时被回调(包括连接失败,发送失败等)。
步骤三:
private void connect() {
EchoWebSocketListener listener = new EchoWebSocketListener();
Request request = new Request.Builder()
.url("ws://echo.websocket.org")
.build();
OkHttpClient client = new OkHttpClient();
// 开启
client.newWebSocket(request, listener);
//关闭
// client.dispatcher().executorService().shutdown();
}
如果打印成功,就说明整个简单的流程走通啦。
如果这个时候出现SSL HandShake的问题 ,那么你需要忽略证书:
public static OkHttpClient getUnsafeOkHttpClient() {
try {
final TrustManager[] trustAllCerts =new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[]getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder =new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder.build();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
将以上 OkHttpClient client = new OkHttpClient();
替换为OkHttpClient client =getUnsafeOkHttpClient();
即可运行
祝君好运