• 安卓websocket 封装基于Java-websocket


    本文借鉴于https://blog.csdn.net/u013872857/article/details/79190643感谢大神的贡献

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

    而这里所用的是:Java-WebSocket:1.3.0

    核心代码如下:

    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 文件

    其主要功能是:

    实现websocket 连接过程中几个行为:IWebSocket,

    提供具体的服务绑定,

    开启websocket 连接线程,回调消息处理等

    其他代码不多加赘述,请先看借鉴文章,之后便对此一目了然,如有不懂,可在下方评论区留言,

    谢谢!

  • 相关阅读:
    php数组操作
    DedeCMS栏目页调用当前栏目名和上级栏目名
    ThinkPHP递归删除栏目
    WebUploader
    js中的事件委托或是事件代理
    thinkphp框架if标签条件表达式
    sublime插件安装
    thinkphp分页
    织梦自定义变量使用
    php foreach用法和实例
  • 原文地址:https://www.cnblogs.com/linwen5723/p/9006867.html
Copyright © 2020-2023  润新知