zoukankan      html  css  js  c++  java
  • Android 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("断开连接");
            }
    
        }
  • 相关阅读:
    CI 搭建CMS框架
    java 对象
    JAVA 数组,(java核心技术 卷1)
    Android 点击事件,4种回调。
    andriod 中设置sdk升级代理服务器
    CI 自动操作日志
    CI 笔记 datagrid的调用,不支持多页面多次调用js
    CI 笔记 easyui 结合后,左侧导航跳转问题
    CI 笔记 数据库
    mysql索引提高查询速度
  • 原文地址:https://www.cnblogs.com/tangchun/p/9328298.html
Copyright © 2011-2022 走看看