基于okhttp3.0的WebSocket的简易实践

工作日志记录:工作中有个需求就是实现实时推送,实时推送基本上都是要基于Socket通讯技术的,这里使用okhttp3.0提供的WebSocket框架,现记录下来便于后面使用时更快;

具体代码如下:

package com.haocang.waterpro.mango;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import androidx.annotation.Nullable;

import com.haocang.commonui.route.MangoRouteURL;
import com.haocang.core.utils.StringUtils;
import com.haocang.core.utils.ToastUtils;
import com.haocang.core.utils.cache.CacheHelper;
import com.haocang.waterpro.utils.NotificationUtils;

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

import java.lang.ref.WeakReference;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocketListener;
import okio.ByteString;


/**
 * 文件描述:WebSocket获取推送信息
 * 作者:徐干稳
 * 创建时间:2019/10/30
 * 更改时间:2019/10/30
 * 版本号:1.0
 */
public class LocalWebSocketService extends Service {

    private MyHandler handler;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        handler = new MyHandler(new WeakReference(this).get());
        String url = "ws://172.19.1.130:18432/web-socket/" +CacheHelper.get("login_name");
        start(url);
        return START_STICKY;
    }

    @Override
    public boolean stopService(Intent name) {
        return super.stopService(name);
    }

    private void start(String wsUrl) {
        Request request = new Request.Builder().url(wsUrl).build();
        OkHttpClient client = new OkHttpClient();
        client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(okhttp3.WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
//                handler.obtainMessage(0, "WebSocket开启").sendToTarget();
//                webSocket.send("收到消息了吗");
            }

            @Override
            public void onMessage(okhttp3.WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                handler.obtainMessage(1, text).sendToTarget();
            }

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

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

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

            @Override
            public void onFailure(okhttp3.WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                handler.obtainMessage(4, "WebSocket连接已关闭").sendToTarget();
            }
        });
        client.dispatcher().executorService().shutdown();
    }

    public class MyHandler extends Handler {
        private Context context;

        public MyHandler(Context context) {
            this.context = context;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != context) {
                switch (msg.what) {
                    case 1:
                        String json = (String) msg.obj;
                        if (!StringUtils.isEmpty(json)) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                               
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    case 4:
                        ToastUtils.showShort((String) msg.obj);
                        break;
                    case 0:
                        ToastUtils.showShort((String) msg.obj);
                        break;
                }
            }
        }
    }
}

 

你可能感兴趣的:(移动开发)