用okhttp实现webSocket长连接

因为项目需求极光不能满足当前推送量,只能寻别的改决方法。想到了webSocket,

Okhttp支持webSocket协议。

上代码:

在 build.gradle 配制 okhttp依赖

 

 compile 'com.squareup.okhttp3:okhttp:3.4.1'

 

 加入网络权限:

 

 


java 代码

创建一OkHttpClient 对像
 
final static OkHttpClient mOkHttpClient = new OkHttpClient.Builder() .readTimeout(3000, TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(3000, TimeUnit.SECONDS)//设置写的超时时间 .connectTimeout(3000, TimeUnit.SECONDS)//设置连接超时时间 .build();
 
设置webSocket连接,回调
 
 String url = "ws://10.0.0.20:8080/hyt/websocket.do?userId=1&userType=2"; //改成自已服务端的地址 
        Request request = new Request.Builder().url(url).build();
        WebSocketCall webSocketCall = WebSocketCall.create(mOkHttpClient, request);
        webSocketCall.enqueue(new WebSocketListener() {
            private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
            private WebSocket webSocket;

            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d("WebSocketCall", "onOpen");
                this.webSocket = webSocket;
            }

            /**
             * 连接失败 * @param e * @param response Present when the failure is a direct result of the response (e.g., failed * upgrade, non-101 response code, etc.). {@code null} otherwise.
             */
            @Override
            public void onFailure(IOException e, Response response) {
                Log.d("WebSocketCall", "onFailure");
            }

            /**
             * 接收到消息 * @param message * @throws IOException
             */
            @Override
            public void onMessage(ResponseBody message) throws IOException {
                final RequestBody response;
                Log.d("WebSocketCall", "onMessage:" + message.source().readByteString().utf8());
                if (message.contentType() == WebSocket.TEXT) {// response = RequestBody.create(WebSocket.TEXT, "你好");//文本格式发送消息 } else { BufferedSource source = message.source(); Log.d("WebSocketCall", "onMessage:" + source.readByteString()); response = RequestBody.create(WebSocket.BINARY, source.readByteString()); } message.source().close(); sendExecutor.execute(new Runnable() { @Override public void run() { try { Thread.sleep(1000*60); webSocket.sendMessage(response);//发送消息 } catch (IOException e) { e.printStackTrace(System.out); } catch (InterruptedException e) { e.printStackTrace(); } } }); } @Override public void onPong(Buffer payload) { Log.d("WebSocketCall", "onPong:"); } /** * 关闭 * @param code The RFC-compliant * status code. * @param reason Reason for close or an empty string. */ @Override public void onClose(int code, String reason) { sendExecutor.shutdown(); } });


                }


            }

 

 

 

url地址改成自已服务端的地址

 

 

 
连接成功会回调onOpen()方法,可以拿到WebSocket对像,连接失败回调onFailure()方法,
服务端推送消息,我们可以通过onMessage()方法接收,同时我们也可以通过WebSocket对像的sendMessage方法给服务端发送消息。
以上完成
 
 
源码下载地址:http://download.csdn.net/detail/tong6320555/9611640

 

你可能感兴趣的:(用okhttp实现webSocket长连接)