使用OkHttp的WebSocket实现长连接

发送心跳包(定时检查是否连接状态)

private long sendTime = 0L;
    // 发送心跳包
    private Handler mHandler = new Handler();
    // 每隔2秒发送一次心跳包,检测连接没有断开
    private static final long HEART_BEAT_RATE = 10 * 1000;
    // 发送心跳包
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
            if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                //发送心跳包
                String message = "{\"type\":\"quote\"}";
                mWebSocket.send(message);
                sendTime = System.currentTimeMillis();
            }
            mHandler.postDelayed(this, HEART_BEAT_RATE); //每隔一定的时间,对长连接进行一次心跳检测
        }
    };

初始化的时候

 // 刚进入界面,就开启心跳检测
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);
        connectWebSocket();

WebSocket返回的状态(注意返回的数据在子线程中,如果进行更新ui需要在主线程中更新,)

public void connectWebSocket() {
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)//允许失败重试
                .readTimeout(5, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(5, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        String url = "ws://www.trbbex.com/websocket";//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);
                mWebSocket = webSocket;
                webSocket.send("{\"type\":\"quote\"}");
                //连接成功
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text); //这里是子线程,不能再子线程中更新ui
                if (text.contains("connect")) {
                    return;
                } else {
                    list = new Gson().fromJson(text, WebBean.class).getData();
                    // 往handler发送一条消息 更改button的text属性
                    Message message = handler.obtainMessage();
                    message.obj=list;
                    message.what = 20;
                    handler.sendMessage(message);
                }
            }


            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);

            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
                super.onFailure(webSocket, t, response);
                //连接失败调用 异常信息t.getMessage()   
                //要延迟关闭socket
           try {
                    webSocket.close(1000, null);
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            connectWebSocket();
                        }
                    },2000);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

```css
 @Override
    public void onDestroy() {
        super.onDestroy();
        // 清除handler后,就不能再发送数据了
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (mWebSocket != null) {
            mWebSocket.close(1000, null);
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        //清空handler
        if (handler!=null){
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

你可能感兴趣的:(使用OkHttp的WebSocket实现长连接)