写点什么

如何使用 OkHttp 实现 websocket

用户头像
Changing Lin
关注
发布于: 15 小时前
如何使用OkHttp实现websocket

1.简介

在分析 OkHttp 源码结构的时候,常常可以发现 WebSocket 的英文、变量、参数及方法。查阅官方数据手册,也有说明:

OkHttp v3.5 now includes support for bidirectional web sockets. The URL that should be used should be prefixed with ws:// or wss:// for the secure version. Although the connection ports are the same as HTTP (port 80 and port 443), the server still needs to be configured to support WebSockets since they are a completely different protocol.

2.代码

private void wssTest(){        OkHttpClient client = new OkHttpClient.Builder()                .pingInterval(50, TimeUnit.MILLISECONDS)                .build();        Request request = new Request.Builder()                .url("ws://127.0.0.1:2000")                .addHeader("query", "clientParam=androidRoom")                .build();        client.newWebSocket(request, new WebSocketListener() {            @Override            public void onOpen(WebSocket webSocket, Response response) {                super.onOpen(webSocket, response);                Log.e(TAG, "onOpen: "+response);            }
@Override public void onMessage(WebSocket webSocket, String text) { super.onMessage(webSocket, text); Log.e(TAG, "onMessage: "+text); }
@Override public void onMessage(WebSocket webSocket, ByteString bytes) { super.onMessage(webSocket, bytes); Log.e(TAG, "onMessage ByteString: "+bytes); }
@Override public void onClosing(WebSocket webSocket, int code, String reason) { super.onClosing(webSocket, code, reason); Log.e(TAG, "onClosing: "+code+reason); }
@Override public void onClosed(WebSocket webSocket, int code, String reason) { super.onClosed(webSocket, code, reason); Log.e(TAG, "onClosed: "+code+reason); }
@Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { super.onFailure(webSocket, t, response); t.printStackTrace(); Log.e(TAG, "onFailure: "+response); } }); }
复制代码

3.总结

  • 往 WebSocket 中发送数据

websocket.send("hello");
复制代码
  • 关闭 WebSocket

webSocket.close(1000, "closing");
复制代码
  • Demo 输出的日志

W/System.err: java.net.ProtocolException: Expected HTTP 101 response but was '400 Bad Request'W/System.err:     at okhttp3.internal.ws.RealWebSocket.checkResponse(RealWebSocket.java:215)W/System.err:     at okhttp3.internal.ws.RealWebSocket$2.onResponse(RealWebSocket.java:182)W/System.err:     at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)W/System.err:     at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)W/System.err:     at java.lang.Thread.run(Thread.java:818)E/cclin: onFailure: Response{protocol=http/1.1, code=400, message=Bad Request, url=http://127.0.0.1:2000/}I/System.out: [CDS]close[38706]I/NetworkManagementSocketTagger: untagSocket(30)D/FlymeTrafficTracking: untag(30) com.example.hellojnicallback OkHttp http://127.0.0.1:2000/... uid 10135 76ms
复制代码


发布于: 15 小时前阅读数: 4
用户头像

Changing Lin

关注

获得机遇的手段远超于固有常规之上~ 2020.04.29 加入

我能做的,就是调整好自己的精神状态,以最佳的面貌去面对那些未曾经历过得事情,对生活充满热情和希望。

评论

发布
暂无评论
如何使用OkHttp实现websocket