一,在模塊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("斷開連接"); } }