WebSocket Android Client Implementation (iii) – Service-side proactive notification

Source: Internet
Author: User

WebSocket Android Client Implementation (iii) – Service-side proactive notification
  
This article is still the last one to continue to expand, have not seen the previous blog's small partners, here are attached to the previous address
  
WebSocket Android Client Implementation (i) – Connection building and reconnection
  
WebSocket Android Client Implementation (ii) – client sends request
  
Finally is the last article, a little excited \ (≧▽≦)/La La La,
  
Service-Side Proactive notification
  
After the warm-up, let's review the process of proactive notification on the service side in the first article
  
The corresponding processing class is found according to the event type in notify, and the corresponding logic is processed.
  
The corresponding UI update is then notified with Eventbus.
  
If an ACK is required, an ACK request is sent.
  
The format of the service-side active notification protocol in the second chapter of the review
  
{
  
"Resp_event": 20,
  
"Action": "",
  
"seq_id": 11111111,
  
According to Resp_event, we judge that this response is a service-side active notification, then the corresponding processing class is found through action, and then the corresponding business logic is executed by parsing the data in the RESP into the corresponding bean incoming corresponding processing class.
  
Show Code
  
public class Wsmanager {
  
.... Omit the same code as before .....
  
Class Wslistener extends Websocketadapter {
  
@Override
  
public void Ontextmessage (WebSocket WebSocket, String text) throws Exception {
  
Super.ontextmessage (websocket, text);
  
LOGGER.T (TAG). D ("receivermsg:%s", text);
  
Response Response = codec.decoder (text);//Parse out the first layer bean
  
if (response.getrespevent () = = 10) {//Response
  
Callbackwrapper wrapper = www.wmyl166.cn Callbacks.remove (
  
Long.parselong (Response.getseqid ()));//Find corresponding callback
  
if (wrapper = = null) {
  
LOGGER.T (TAG). D ("(action:%s) not found www.xingchexiu.com callback", Response.getaction ());
  
Return
  
}
  
try {
  
Wrapper.gettimeouttask (). Cancel (true);//Cancels timeout task
  
Childresponse childresponse = Codec.decoderchildresp (
  
Response.getresp ());//parsing the second-tier bean
  
if (Childresponse.isok ()) {
  
Object o = new Gson (). Fromjson (Childresponse.getdata (),
  
Wrapper.getaction (). Getrespclazz ());
  
Wrapper.gettempcallback (). onsuccess (o);
  
} else {
  
Wrapper.gettempcallback ()
  
. OnError (ERRORCODE.BUSINESS_EXCEPTION.GETMSG (), Wrapper.getrequest (),
  
Wrapper.getaction ());
  
}
  
} catch (Jsonsyntaxexception e) {
  
E.printstacktrace ();
  
Wrapper.gettempcallback ()
  
. OnError (ERRORCODE.PARSE_EXCEPTION.GETMSG (), Wrapper.getrequest (),
  
Wrapper.getaction ());
  
}
  
} else if (response.getrespevent () = = 20) {//notification
  
Notifylistenermanager.getinstance (). Fire (www.chuangyed.com response);

We first parse out the first tier bean and then execute the NOTIFYLISTENERMANAGER notification management class for the fire () method based on Resp_event for 20.
  
public class Notifylistenermanager {
  
Private final String TAG = This.getclass (). Getsimplename ();
  
Private volatile static Notifylistenermanager manager;
  
Private map<string, inotifylistener> Map = new hashmap<> ();
  
Private Notifylistenermanager () {
  
Regist ();
  
}
  
public static Notifylistenermanager getinstance () {
  
if (manager = = null) {
  
Synchronized (Notifylistenermanager.class) {
  
if (manager = = null) {
  
Manager = new Notifylistenermanager ();
  
}
  
}
  
}
  
Return manager;
  
}
  
private void Regist () {
  
Map.put ("Notifyannouncemsg", New Announcemsglistener ());
  
}
  
public void Fire (Response Response) {
  
String action = Response.getaction ();
  
String resp = Response.getresp ();
  
Inotifylistener listener = map.get (action);
  
if (listener = = null) {
  
LOGGER.T (TAG). D ("No found notify listener");
  
Return
  
}
  
Notifyclass Notifyclass = Listener.getclass (). Getannotation (Notifyclass.class);
  
Class<?> clazz = Notifyclass.value ();
  
Object result = null;
  
try {
  
result = new Gson (). Fromjson (resp, clazz);
  
} catch (Jsonsyntaxexception e) {
  
E.printstacktrace ();
  
}
  
LOGGER.T (TAG). D (Result);
  
Listener.fire (result);

Notifylistenermanager is a singleton class that executes the Regist method in the constructor method at the time of the first creation, which is a variant of the observer pattern for adding observers to this process we have written directly in the Regist method, If new business logic is added we only need to put the newly added action and corresponding processing class in the Regist method. Externally exposed fire method finds the corresponding processing class according to the action in the incoming Responsse, and gets the class of the annotation tag corresponding to the processing class. Parse the RESP returned by the server into the corresponding bean and throw it to the corresponding processing class to execute the corresponding logic.
  
Abstract interface
  
Public interface Inotifylistener<t> {
  
void Fire (T t);
  
}
  
Tag annotations
  
@Target (Elementtype.type)
  
@Retention (Retentionpolicy.runtime)
  
@Documented
  
Public @interface Notifyclass {
  
Class<?> value ();
  
}
  
Processing sub-classes for specific logical correspondence
  
@NotifyClass (Announcemsgnotify.class)
  
public class Announcemsglistener implements inotifylistener<announcemsgnotify> {
  
@Override
  
public void Fire (announcemsgnotify www.wmyl110.com announcemsgnotify) {
  
Here, we deal with specific logic.
  
}
  
}
  
corresponding Data bean
  
public class Announcemsgnotify {
  
@SerializedName ("Msg_version")
  
Private String msgversion;
  
Public String getmsgversion () {
  
return msgversion;
  
}
  
public void Setmsgversion (String msgversion) {
  
This.msgversion = msgversion;

If we add new business logic, we just need to implement the business logic class, and then put new action and listener mappings in Notifylistenermanager's www.wmyl119.cn regist method. You only need to call Notifylistenermanager.getinstance (). Fire (response) to achieve understanding decoupling.
  
WebSocket .... Applause and applause.
  
Summarize
  
For the use of WebSocket I have done my best to explain the most detailed, but also can not avoid some omissions and mistakes also hope that the small partners pointed out.
  
And then although I wrote three articles but there are a few points that are not detailed enough, here I have listed the interests of the small partners can see for themselves.
  
Get the connection address and select a connection address policy
  
Re-connected policies
  
The strategy of the Heartbeat
  
Process KeepAlive
  
Finally thanks to all the small partners to join the three can be finished reading is absolutely true love ah ...

WebSocket Android Client Implementation (iii) – Service-side proactive notification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.