安卓websocket 封裝基於Java-websocket

本文借鑑於https://blog.csdn.net/u013872857/article/details/79190643感謝大神的貢獻java

借鑑文章所用websocket 第三方是:nv-websocket-client:2.2,web

而這裏所用的是:Java-WebSocket:1.3.0服務器

核心代碼以下:websocket

public abstract class MyWebSocketService extends Service implements IWebSocket {

    private static final String TAG = MyWebSocketService.class.getSimpleName();
    private ServiceBinder binder = new ServiceBinder();

    private int connectStatus = 0;

    private WebSocketThread webSocketThread;
    private WebSocketClient client;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        if (binder == null){
            binder = new MyWebSocketService.ServiceBinder();
        }
        return binder;
    }
    public class ServiceBinder extends Binder {
        public  MyWebSocketService getService() {
            return MyWebSocketService.this;
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
        // 鏈接
        webSocketThread = new MyWebSocketService.WebSocketThread();
        webSocketThread.start();


    }
    private class WebSocketThread extends Thread {
        @Override
        public void run() {
            Log.i(TAG, "run: ");
            setupWebSocket();
        }
    }

    protected void setupWebSocket(){
        Log.i(TAG, "setupWebSocket: ");
        if (connectStatus != 0) return;
        connectStatus = 1;
        try {
            client = new WebSocketClient(URI.create(getConnectUrl()), new Draft_10()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    connectStatus = 2;
                }

                @Override
                public void onMessage(String message) {
                    Log.i(TAG, "onMessage: " + message);
                    // 消息分發
                    dispatchResponse(message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.e(TAG, "onClose: " + code + reason);
                    connectStatus = 0;
                    // EventBus 通知

                }

                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "onError: " + ex.getMessage());
                    connectStatus = 0;
                    // EventBus 通知
                }

            };
            client.connect();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }


    @Override
    public void sendText(String text) {
        Log.i(TAG, "sendText From Four Activity : " + text);
        if (TextUtils.isEmpty(text)) return;
        if (client != null && connectStatus == 2){
            client.send(text);
        }
    }

    @Override
    public int getConnectStatus() {
        return connectStatus;
    }

    @Override
    public void reconnect() {
        Log.i(TAG, "reconnect: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (webSocketThread != null && webSocketThread.isAlive()){
                    connectStatus = 0;
                    webSocketThread = new WebSocketThread();
                    webSocketThread.start();
                }else {
                    Log.e(TAG, "run: reconnect action is Failed " );
                }
            }
        }).start();
    }

    @Override
    public void stop() {
        Log.i(TAG, "stop: ");
        client.close();
        connectStatus = 0;
    }

    /**
     *  獲取服務器地址
     * @return
     */
    protected abstract String getConnectUrl();


    /**
     * 分發響應數據
     */
    protected abstract void dispatchResponse(String textResponse);


}

同借鑑文章中 AbsBaseWebSocketService.java 文件socket

其主要功能是:ide

實現websocket 鏈接過程當中幾個行爲:IWebSocket,this

提供具體的服務綁定,spa

開啓websocket 鏈接線程,回調消息處理等.net

其餘代碼很少加贅述,請先看借鑑文章,以後便對此一目瞭然,若有不懂,可在下方評論區留言,線程

謝謝!

相關文章
相關標籤/搜索