欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android WebSocket开发

程序员文章站 2022-04-11 20:59:09
一,在模块build.gradle中添加webSocket的依赖包 二,连接webSocket 三、添加内部类,实现回调监听 ......

一,在模块build.gradle中添加webSocket的依赖包

//WebSocket 依赖包
implementation 'com.neovisionaries:nv-websocket-client:2.2'

二,连接webSocket

  try {
          WebSocket ws = new WebSocketFactory().createSocket(url, CONNECT_TIMEOUT) //ws地址,和设置超时时间
                    .setFrameQueueSize(FRAME_QUEUE_SIZE)//设置帧队列最大值为5
                    .setMissingCloseFrameAllowed(false)//设置不允许服务端关闭连接却未发送关闭帧
                    .addListener(wsListener = new WsListener())//添加回调监听
                    .connectAsynchronously();//异步连接

        } catch (IOException e) {
            e.printStackTrace();
        }

三、添加内部类,实现回调监听

/**
     * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
     * onTextMessage 收到文字信息
     * onConnected 连接成功
     * onConnectError 连接失败
     * onDisconnected 连接关闭
     */
    class WsListener extends WebSocketAdapter {
        @Override
        public void onTextMessage(WebSocket websocket, String text) throws Exception {
            super.onTextMessage(websocket, text);
            logger.info(text);
            String[] msgs = text.split("\\|");
            if (msgs.length >= 2) {
                NotificationShow(msgs[0], msgs[1]);
                sendReceiveMessageBroadcast(msgs[0], msgs[1]);
            }
        }

        @Override
        public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
                throws Exception {
            super.onConnected(websocket, headers);
            logger.info("连接成功");
        }

        @Override
        public void onConnectError(WebSocket websocket, WebSocketException exception)
                throws Exception {
            super.onConnectError(websocket, exception);
            logger.warning("连接错误:" + exception.getMessage());
        }

        @Override
        public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
                throws Exception {
            super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
            logger.warning("断开连接");
        }

    }