android 中okhttp3 的webSocket 使用

@BindView(R.id.titlebar)
BGATitleBar titlebar;
@BindView(R.id.lv_price)
ListView lvPrice;
WebSocket mSocket;
private List data;
private List newData;
private PriceAdapter adapter;
/**
 *  
 */

@Override
protected void initData() {
    newData = new ArrayList<>();
}

private void initAdapter() {
    adapter = new PriceAdapter(getActivity(), newData);
    lvPrice.setAdapter(adapter);
}
/** 主要部分
 * webSocket listener
 */
class EchoWebSocketListener extends WebSocketListener {
    @Override
    public void onOpen(okhttp3.WebSocket webSocket, Response response) {
        mSocket = webSocket;
        LogUtils.e("client onOpen");
        LogUtils.e("client request header:" + response.request().headers());
        LogUtils.e("client response header:" + response.headers());
        LogUtils.e("client response:" + response);
        mSocket.send("socket");
        LogUtils.e("连接成功!");

    }


    @Override
    public void onMessage(okhttp3.WebSocket webSocket, ByteString bytes) {
        super.onMessage(webSocket, bytes);
        LogUtils.e("receive bytes:" + bytes.hex());
    }

    @Override
    public void onMessage(okhttp3.WebSocket webSocket, final String text) {
        super.onMessage(webSocket, text);
        LogUtils.e("receive text:" + text);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    String code = jsonObject.optString("code");
                    if (code.equals("0")) {
                        Gson gson = new Gson();
                        QuotationInfo quotationInfo = gson.fromJson(text, QuotationInfo.class);
                        data = quotationInfo.getData();
                        newData.clear();
                        newData.addAll(data);
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onClosed(okhttp3.WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);
        LogUtils.e("closed:" + reason);
    }

    @Override
    public void onClosing(okhttp3.WebSocket webSocket, int code, String reason) {
        super.onClosing(webSocket, code, reason);
        LogUtils.e("closing:" + reason);
    }

    @Override
    public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        LogUtils.e("failure:" + t.getMessage());
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    LogUtils.e("onDestoryView");
}

/**
 * 切换fragment 加载   fragment之间切换   onResume等等  则不会执行  故有两处重新加载
 */
@Override
public void onHiddenChanged(boolean hidden) {
    if (!hidden) {
        OkhttpUtils.doWebSocket(getActivity(), "此处换成自己的web地址  ws、wss这些", new EchoWebSocketListener());
        initAdapter();
    } else {
        if (mSocket != null) {
            OkhttpUtils.getInstance(getActivity()).dispatcher().cancelAll();
        }
    }
}

/**
 * 页面暂停时 断开socket
 */
@Override
public void onPause() {
    super.onPause();
    LogUtils.e("onPause");
    if (mSocket != null) {
        OkhttpUtils.getInstance(getActivity()).dispatcher().cancelAll();
    }
}

/**
 * 页面重新激活时,重新加载(App退出后台时)
 */
@Override
public void onResume() {
    super.onResume();
    LogUtils.e("onResume");
    OkhttpUtils.doWebSocket(getActivity(), "此处为自己的地址", new EchoWebSocketListener());
    initAdapter();
}

 

 

 

okhttp 工具类

 

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.WebSocketListener;


/**
 * Created by xieyaxin on 2018/9/6.
 */

public class OkhttpUtils {
    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    private static OkHttpClient client = null;
    private static HashMap> cookieStore;
    private static final int READ_BYSOKET = 1001;

    private OkhttpUtils() {}


    public static OkHttpClient getInstance(Context context) {
        if (client == null) {
            //保存cookie
            ClearableCookieJar cookieJar =
                    new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
            synchronized (OkhttpUtils.class) {
                if (client == null)
                    client = new OkHttpClient.Builder()
                          .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                          .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                          .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                            .cookieJar(cookieJar)
                            .build();
            }
        }
        return client;
    }

    /**
     * webSocket
     */
    public static void doWebSocket(Context context, String url, WebSocketListener webSocketListener) {
        Request request = new Request.Builder().url(url).build();
        getInstance(context).newWebSocket(request, webSocketListener);
    }
}

你可能感兴趣的:(webSocket)