Step-by-step learning WebSocket (2) Programming WebSocket

Source: Internet
Author: User

Next, this article uses the programming websocket to implement the previous example:


Service-side endpoint, no longer using serverendpoint annotations:

public class programerserver extends endpoint {     @Override     public void onopen (SESSION&NBSP;SESSION,&NBSP;ENDPOINTCONFIG&NBSP;EDC)   {        system.out.println ("somebody is coming!");                  Session.addmessagehandler (new messagehandler.whole<string> ()  {              @Override              public void onmessage (string message)  {      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (message);                  try {           &nBsp;         session.getbasicremote (). SendText ("it is  Sickening ");                 }  catch  (ioexception e)  {                     e.printstacktrace ();                 }             }        });    }     @Override    public void onclose (Session session, closereason  closereason)  {        // no-op by default     }    @Override     public void onerror ( session session,  throwable throwable)  {        // NO-OP by  default    }}

Instead of inheriting a endpoint-like class, we found that the endpoint provides three methods: Onopen,onclose,onerror.

With the four-piece set that exists in the declarative websocket: @OnOpen, @OnClose, @OnMessage, @OnError, compared to less @onmessage.

What's the callback after we get the message? From the code above you can see that the MessageHandler added to the session has a similar method onmessage. Yes, that's him. The handler OnMessage method that receives the message is called.


Is there a difference in the running logic of the two programming modes? In fact, for declarative programming, it is also a method of @onmessage markup by MessageHandler callback. Just this process in declarative programming mode, was packaged by Tomcat and so on.


(Here, for declarative programming, Tomcat translates it into this pattern of cost-pojo, declarative programming does not inherit the endpoint class, and Tomcat constructs a subclass of endpoint, In the TOMCAT8 called Pojoendpointserver. The following inheritance relationships:

public class Pojoendpointserver extends Pojoendpointbasepublic abstract class Pojoendpointbase extends Endpoint.

The back end of the run using pojoendpointserver entrusted to our Pojo class can be, the same reason

The Pojo of the @ClientEndpoint annotation corresponds to pojoendpointclient. )


found no, no serverendpoint annotations, unable to configure the mapping path for the endpoint? Here we need to declare a serverapplicationconfig entity (also remembered and restful The javax.rs.ws.core.Application in WS? ) to complete this function:

public class myapplicationconfig implements serverapplicationconfig{      @Override     public set<class<?>> getannotatedendpointclasses ( set<class<?>> allclasses)  {        return  null;    }     @Override     public Set< Serverendpointconfig> getendpointconfigs (set<class<? extends endpoint>> end )  {        ServerEndpointConfig sec =   ServerEndpointConfig.Builder.create (programerserver.class,  "/chat")          .configurator (New serverendpointconfig.configurator () {         }). Build ();                    &nbSp;   return new hashset<serverendpointconfig> () {{            add (sec);       }};     }}

Getendpointconfig constructs a Serverendpointconfig collection, the previous declarative websocket why don't you need this? As needed, Only in declarative websocket can tomcat build him by @serverendpoint annotations. See Tomcat code:

  @Override     public void addendpoint (Class<?> pojo)  throws  deploymentexception {        serverendpoint annotation  = pojo.getannotation (Serverendpoint.class);               // ServerEndpointConfig         serverendpointconfig sec;        class<? extends  configurator> configuratorclazz =                 annotation.configurator ();         configurator configurator = null;        if  (! Configuratorclazz.equals (Configurator.class))  {             try {&nbSp;               configurator  = annotation.configurator (). newinstance ();             } catch  (instantiationexception | illegalaccessexception e)  {                 throw new  deploymentexception (Sm.getstring (                          " Servercontainer.configuratorfail ",                         annotation.configurator (). GetName (),                          pojo.getclass (). GetName ()), e);            }         }        sec =  ServerEndpointConfig.Builder.create (Pojo, path) .                 decoders (Arrays.aslist (Annotation.decoders ())) .                 encoders (Arrays.asList ( Annotation.encoders ())) .                 subprotocols (Arrays.aslist (Annotation.subprotocols ())) .                 configurator (Configurator) .                 build ();         addendpoint (sec);     } 

Tomcat constructs a serverendpointconfig for each of the serverendpoint.


Put the above two classes at the same time, into the war package, deployed to Tomcat, a websocket server is OK.


Now you can use the client of the previous article to access the WebSocket. Or you are tired of annocation. Let's have a programming client:

public class programerclient extends endpoint {     @Override     public void onopen (SESSION&NBSP;SESSION,&NBSP;ENDPOINTCONFIG&NBSP;EDC)   {        system.out.println ("I was accpeted by her !");         session.addmessagehandler (new messagehandler.whole< String> ()  {             @Override              public void onmessage (String  Message)  {                 system.out.println ("she say: "  + message);              }        });     }}

Why is there no Onclose,onerror method? Because there is a default implementation in endpoint, there is no overload here.

Public class client {    public static void main (String[]  args)  throws DeploymentException, IOException, InterruptedException {         WebSocketContainer ws =  Containerprovider.getwebsocketcontainer ();         string url  =  "Ws://localhost:8080/chatweb2/chat";                 ClientEndpointConfig cec =  ClientEndpointConfig.Builder.create (). Configurator (New myclientconfigurator ()). Build ();         session session = ws.connecttoserver (PROGRAMERCLIENT.CLASS,CEC, Uri.create (URL));         session.getbasicremote (). SendText ("Hello, Chick! ");         thread.currentthread (). Sleep (10000);     }} 

Wait, it's a little different. Of course, there is no clientendpoint here, of course there is no @clientendpoint.configurator field (remember the structure of @clientendpoint?). )

Of course, there is no clientendpointconfig. So we need to add one to our own.


You can see that the programmatic websocket endpoint is a lot more complex than annotation. Using annotation tips to make programming easier,

For WebSocket containers (that is, Tomcat in this article) you need to convert this annotation hint into execution code.


For everyone to have a whole understanding of the two modes, we skipped the middle details. I hope we don't have any obstacles to our understanding.


This article from "The World No Thief" blog, declined reprint!

Step-by-step learning WebSocket (2) Programming WebSocket

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.