okhttp3连接websocket

由于度娘找的都是一堆废话,所以,自己实现了,留待以后使用:

1、在build.gradle中的dependencies中加载okhttp3(其他的加载方式在okhttp的gihub地址:https://github.com/square/okhttp介绍比较详细)

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

2、创建连接到websocket的代码

OkHttpClient client = new OkHttpClient.Builder().readTimeout(0,  TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url("ws://10.254.20.222:9502").build();
        client.newWebSocket(request, this);
        client.dispatcher().executorService().shutdown();

3、写一个类继承okhttp3的WebSocketListener,实现其中的方法,对第二步建立websocket进行监听就可以了。


下面是实现的一个类:

package com.example.asus.myapplication;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;
import okhttp3.WebSocket;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocketListener;
import okio.ByteString;

public final class ChatWebSocket extends WebSocketListener {
    private WebSocket _WebSocket=null;
    private JSONObject _JsonObject=null;

    private static ChatWebSocket mChatWebSocket=null;


    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        _WebSocket=webSocket;
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.e("MESSAGE>>>>>>>",text);
        try {
             _JsonObject = new JSONObject(text);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        System.out.println("MESSAGE: " + bytes.hex());
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        webSocket.close(1000, null);
        mChatWebSocket=null;
        Log.e("Close:",code+reason);
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        t.printStackTrace();
    }

    /**
     * 初始化WebSocket服务器
     */
    private void run() {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(0,  TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder().url("ws://10.254.20.222:9502").build();
        client.newWebSocket(request, this);
        client.dispatcher().executorService().shutdown();
    }

    /**
     *
     * @param s
     * @return
     */
    public boolean sendMessage(String s){
        return _WebSocket.send(s);
    }

    public void closeWebSocket(){
        mChatWebSocket=null;
        _WebSocket.close(1000,"主动关闭");
        Log.e("close","关闭成功");
    }

    /**
     * 获取全局的ChatWebSocket类
     * @return ChatWebSocket
     */
    public static ChatWebSocket getChartWebSocket(){
        if(mChatWebSocket==null) {
            mChatWebSocket =new ChatWebSocket();
            mChatWebSocket.run();
        }
        return mChatWebSocket;
    }

}

4、实现一个观察者类ChatDataObserver,对于回调来的信息做处理:

package com.example.asus.myapplication.ChatRoom;

import org.json.JSONObject;

/**
 * Created by yzq on 2016/12/12
 */

public interface ChatDataObserver {
    void OnMessage(JSONObject jsonObject);
}


5、最后在用到的类中继承ChatDataObserver类中的接口即可监听到websocket的消息,若需要监听别的在回调中增加即可。

你可能感兴趣的:(android)