Android webSocket(okhttp-4.9.0)

开发过程,部分需要webSocket,这里使用 okhttp 自带socket。

一、依赖:com.squareup.okhttp3:okhttp:4.9.0

二、创建webSocket

1、创建okhttpClient和Request

public void init(){
		//初始化okhttpClient
        mBuilder = new OkHttpClient.Builder();
        //设置读取超时时间
        mBuilder.readTimeout(120, TimeUnit.SECONDS);
        //设置写的超时时间
        mBuilder.writeTimeout(120, TimeUnit.SECONDS);
        //设置连接超时时间
        mBuilder.connectTimeout(120, TimeUnit.SECONDS);
        //心跳时间
        mBuilder.pingInterval(10,TimeUnit.SECONDS);
        mOkHttpClient = mBuilder.build();
		
		//初始化request 
		mRequest = new Request.Builder().url(socketUrl).build();
}
	

2、创建webSocket并获取socket对象

public void connect(){
		mWebSocket = mOkHttpClient.newWebSocket(mRequest, new WebSocketListener() {
                @Override
                public void onOpen(final WebSocket webSocket, final Response response) {
                    super.onOpen(webSocket, response);
                    //socket 连接成功(需要自己切换到主线程)
                }

                @Override
                public void onMessage(WebSocket webSocket, final String text) {
                    super.onMessage(webSocket, text);
                   //socket 获取String 类型数据(需要自己切换到主线程)
                }

                @Override
                public void onMessage(WebSocket webSocket, ByteString bytes) {
                    super.onMessage(webSocket, bytes);
					//socket 获取ByteString 类型数据(需要自己切换到主线程)
                }

                @Override
                public void onClosing(final WebSocket webSocket, final int code, final String reason) {
                    super.onClosing(webSocket, code, reason);
					
                   
                }

                @Override
                public void onClosed(final WebSocket webSocket, final int code, final String reason) {
                    super.onClosed(webSocket, code, reason);
					//释放连接
                    
                }

                @Override
                public void onFailure(final WebSocket webSocket, final Throwable t, final Response response) {
                    super.onFailure(webSocket, t, response);
                    //其他异常,都会执行这个方法
                }
            });
        }
	}

三、数据交互 mWebSocket.send(msg);

四、关闭webSocket

如果只是关闭连接可采用:

1、mWebSocket.close(code,reason),则WebSocketListener.onClosed()会被调用。这里需要注意是code码,不可以随便传递。可以参考文档 https://tools.ietf.org/html/rfc6455#section-7.4

2、mWebSocket.cancel(),则WebSocketListener.onFailure()会被调用

 

上一篇:耗时两个礼拜,8000字安卓面试长文,经验分享


下一篇:我的头条面试经历分享,灵魂拷问