Step-by-step learning websocket (1) Declarative WebSocket

Source: Internet
Author: User

This section describes declarative WebSocket programming, which can be compared with the latter programming WebSocket:

First on the service side:

@ServerEndpoint ("/chat") public class declarativeserver {     @OnOpen        public void onopen (session session)  {           system.out.println ("somebody is coming!");      }         @OnClose        public void onclose ()  {      }          @OnMessage       public void  OnMessage (string message, session session)  throws IOException {       SYSTEM.OUT.PRINTLN (message);        Session.getbasicremote (). SendText ("it is sickening");    }          @OnError       Public void onerror (Session session, throwable error)  {           error.printstacktrace ();       }  }

A pojo is declared as a WebSocket server endpoint (endpoint and Web service concept endpoint similar) through Serverendpoint annotations.

The Serverendpoint note declares the following:

@Retention (retentionpolicy.runtime) @Target (elementtype.type) public  @interface  serverendpoint {     /**     * URI or URI-template that  the annotated class should be mapped to.     * @ Return the uri or uri-template that the annotated class should  be mapped     *         to.      */    string value ();     string[]  subprotocols ()  default {};    class<? extends decoder>[]  decoders ()  default {};    Class<? extends Encoder>[]  Encoders ()  default {};    public Class<? extends  Serverendpointconfig.configurator>  configurator ()             default  ServerEndpointConfig.Configurator.class;}

In general, we only need to configure the Value property for the Serverendpoint annotation to represent the URL path to the endpoint mapping.

The Subprotocols protocol is used for sub-protocols with WebSocket, such as superchat, which we ignore first.

Decoders,encoders is used to define codecs, and we'll discuss them in detail later in the article.

The Configurator property, for the server endpoint of declarative programming, can be unworthy of value and will be serverendpointconfig.configurator by default.

(with default values, it is generally stated that this property is indispensable, and we will see more details of Configurator when you are in the program WEBSOCKETK).


Declarativeserver implements four methods, with annotated @OnOpen, @OnClose, @OnMessage, @OnError marking.

@OnOpen indicates that when there is a client connected to the endpoint, the callback @onopen the method of the token.

@OnClose when the client disconnects, that is, the service side receives a connection disconnect specified, the callback @onclose method.

@OnMessage The method is recalled when the service side receives the clearing interest.

@OnError The method is invoked when an exception is found on the server, such as a protocol error. Error does not mean that the connection needs to be closed, many errors are recoverable.


Put the class into the war package and deploy to Tomcat, and a websocket server is OK.


This time we do not use JavaScript as the client endpoint, but rather the rich client mode access, Java application.

First define the client endpoint:

@ClientEndpointpublic  class DeclarativeClient {     @OnOpen        public void onopen (session session)  {          system.out.println ("i was accpeted by her!");     }         @OnClose        public void onclose ()  {      }          @OnMessage       public void onmessage ( String message, session session)  {          System.out.println ("she say: "  + message);     }          @OnError       public void onerror ( Session session, throwable error)  {          error.printstacktrace ();       }  }

The Clientendpoint annotation indicates that this is a WebSocket client endpoint.

@Retention (retentionpolicy.runtime) @Target (elementtype.type) public @interface clientendpoint {string[]    Subprotocols () default {}; class<?    Extends decoder>[] Decoders () default {}; class<?    Extends encoder>[] encoders () default {}; Public class<? Extends configurator> Configurator () default Configurator.class;}

With the above serverendpoint only one value attribute, without speaking everyone knows why.

The annotation of each method is no longer restated like server. Main function:

public class Client {public static void main (string[] args) throws Deploymentexception, IOException, interruptedexcept         ion {Websocketcontainer ws = Containerprovider.getwebsocketcontainer ();         String url = "Ws://localhost:8080/chatweb/chat";          Session session = Ws.connecttoserver (Declarativeclient.class, uri.create (URL));         Session.getbasicremote (). SendText ("hello,chick!");    Thread.CurrentThread (). Sleep (10000); }}

Before running the client, you need to import the Tomcat related package, here you can import all, no longer elaborate, interested can self-study.


Containerprovider enables a serviceloader mechanism to load containerprovider implementation classes. and provide Websocketcontainer instances,

On Tomcat, this instance is the Wswebsocketcontainer class.

Gets the Remoteendpoint.basic instance by using the Session.getbasicremote () method to send the message.

A simple WebSocket message is complete.


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

Step-by-step learning websocket (1) Declarative 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.