One, add the WebSocket dependency package in the module Build.gradle
// WebSocket Dependency Package implementation ' com.neovisionaries:nv-websocket-client:2.2 '
Two, connect WebSocket
Try{WebSocket ws=Newwebsocketfactory (). Createsocket (URL, connect_timeout)//WS address, and set time-out . Setframequeuesize (F Rame_queue_size)//Set frame queue maximum value to 5. setmissingcloseframeallowed (false)//setting does not allow the server to close the connection but does not send the close frame. AddListener (Wslistener =NewWslistener ())//Add callback Listener. connectasynchronously ();//Asynchronous Connections } Catch(IOException e) {e.printstacktrace (); }
Third, add internal classes, implement callback monitoring
/*** Inherit the default listener null implementation Websocketadapter, rewrite the method we need * Ontextmessage receive text message * onconnected Connection Successful * Onconnecterror connection lost Fail * ondisconnected connection off*/ classWslistenerextendsWebsocketadapter {@Override Public voidOntextmessage (WebSocket WebSocket, String text)throwsException {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 voidOnconnected (WebSocket WebSocket, map<string, list<string>>headers)throwsException {Super. onconnected (WebSocket, headers); Logger.info ("Connection succeeded"); } @Override Public voidOnconnecterror (WebSocket WebSocket, websocketexception exception)throwsException {Super. Onconnecterror (WebSocket, exception); Logger.warning ("Connection error:" +exception.getmessage ()); } @Override Public voidOndisconnected (WebSocket WebSocket, Websocketframe servercloseframe, Websocketframe clientcloseframe,Booleanclosedbyserver)throwsException {Super. ondisconnected (WebSocket, Servercloseframe, Clientcloseframe, closedbyserver); Logger.warning ("Disconnected"); } }
Android WebSocket Development