WebSocket Combat (2) Information processing send, receive and encode

Source: Internet
Author: User

WebSocket and the traditional socket programming, although there are differences, but also there is a concept of the same, also sub-server and client.

Main differences

    1. For WebSocket, the client is written by JS write callback function to complete the interaction, while the traditional socket, you need to connect the port, through the input and output stream to pass information, complete the interaction;

    2. The traditional socket, the service side needs to bind the port, through the Accept method, waits for the client to connect. The WebSocket specification completes the processing details by the Web server.

Data processing is a major work of WebSocket. Divided by the work stage, mainly includes the following aspects.

    1. Send information

    2. Information decoding

    3. Information encoding

    4. Information reception

By passing the data divided into

    1. Text information

    2. Binary Stream Information

    3. Ping/pong Information

The above content, limited to the service side, WebSocket HTML5 related temporarily not discussed

1. Sending information (sending Messages)

Represents the service side, passing the message to the client (peer)

1.1 Broadcast messages to all connected clients
@ServerEndpoint ("/echoall") public class Echoallendpoint {@OnMessage public void OnMessage (Session session, String MSG {//1 try {for (Session sess:session.getOpenSessions ()) {if (Sess.isopen ()) SES   S.getbasicremote (). SendText (msg);//2,3}} catch (IOException e) {...} }}

Three steps to send information

1.Obtain the Session object from the connection. ( Get session by adding a session to the parameter)

2.Use the Session object to obtain a RemoteEndpoint object.

3.Use the RemoteEndpoint object to send messages to the peer.

1.2 return value, sent as information

@OnMessagepublic string OnMessage (String message,session Session) {System.out.println ("Received:" + message); return message+ "-" +session.getid ();}

2. Decoding and encoding of information (codec)

Take the call for example, if the telephone both sides, all use the same standard Mandarin communication, there is no need to use the translator. If both sides of the telephone, while using the standard Oxford dialect, one side of the standard Shandong dialect, think can also think out, communication directly disorderly dropped, this time must use both sides must both need translator. The encoding and decoding part of the WebSocket is the "translator" role.

Encoding and decoder location

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/87/FB/wKiom1flQOrjYxZkAAA-cTPuJaw973.png "title=" Codec.png "alt=" Wkiom1flqorjyxzkaaa-ctpujaw973.png "/>

Can be simply understood as: decoding is the process of deserialization; encoding is the process of serialization.

2.1 Using Encoders to deserialize an object

The response information needs to be converted to binary for network delivery.

Examples from the Java EE

1. Implement the encoder.text<t> or Encoder.binary<t> interface

public class Messageatextencoder implements encoder.text<messagea> {@Override public void init (Endpointconfig E      c) {} @Override public void Destroy () {} @Override public String encode (Messagea Msga) throws Encodeexception {   Access Msga ' s properties and convert to JSON text ... return msgajsonstring; }}

2. Add the newly created encoder in the first step to the Encoders property of the Serverendpoint annotation

@ServerEndpoint (value = "/myendpoint", encoders = {messageatextencoder.class, messagebtextencoder.class}) public CLA SS Encendpoint {...}

3. Send the object using the SendObject of Remoteendpoint.basic or Remoteendpoint.async.

Messagea MSGA = new Messagea (...); Messageb MSGB = new Messageb (...); Session.getBasicRemote.sendObject (MSGA); Session.getBasicRemote.sendObject (MSGB);

2.2 Using decoders serialization information

Convert request information to objects to facilitate serverpoint processing of responses

Similar to encoders processing steps

1. Implement decoder.text<t> or decoder. Binary <T> interface

public class messagetextdecoder implements decoder.text<message> {     @Override    public void init (ENDPOINTCONFIG&NBSP;EC)  { }     @Override    public void destroy ()  { }    @Override    public message decode (string string)  throws decodeexception {       // Read message...      if  (  /* message is an A message */ )           return new messagea (...);       else if  ( /* message is a B  message */ )          return new messageb (...);    }    @Override    public boolean willdecode (string string)  {      // Determine if  the message can be converted into either a       // MessageA object or a MessageB object...       return candecode;   }}

Note the Willdecode method to determine whether to decode


2. New decoder, added to the decoders attribute of the Serverendpoint annotation

@ServerEndpoint (value = "/myendpoint", encoders = {messageatextencoder.class, messagebtextencoder.class}, decoder s = {Messagetextdecoder.class}) public class Encdecendpoint {...}

3. The object type returned by Decoder.decode can be used directly in the parameter method of the @onmessage annotation.

@OnMessagepublic Void Message (Session session, message msg) {if (msg instanceof Messagea) {//We received a Messa GeA Object ...} else if (msg instanceof Messageb) {//We received a Messageb object ...}}

For specific examples, see my GitHub project. Https://github.com/janecms/websocket_example

    • (XML) Encoding decryption processing (codec)

    • (JSON) Encoded decryption processing (codec)

3. Information reception (receiving Messages)

3.1 Receive three different forms of messages

package com.sample.websocket.endpoint;import javax.websocket.onmessage;import  javax.websocket.pongmessage;import javax.websocket.session;import  javax.websocket.server.serverendpoint;import java.nio.bytebuffer; @ServerEndpoint ("/receive") public  class receiveendpoint {    @OnMessage    public void  TextMessage (session session, string msg)  {       System.out.println ("text message: "  + msg);    }    @ Onmessage   public void textmessage (session session, string msg)   {      system.out.println ("text message: "  + msg);    }    @OnMessage    public void binarymessage (session  SESSION,&NBSP;BYTEBUFFER&NBSP;MSG)  {      system.out.prinTLN ("binary message: "  + msg.tostring ());   }    @OnMessage    public void pongmessage (session session, pongmessage msg)  {       system.out.println ("pong message: "  +   Msg.getapplicationdata (). toString ());    }}

In a strange case, different versions of Tomcat, the method restrictions on @onmessage annotations differ. It is also further explained that the WebSocket specification is a rapidly changing norm. there is a direct compile time error, and some run-time errors. (It may be related to my choice of different versions of the development tools, not quite sure, the same code, behaves differently, odd)

It is important to note that the three methods that are annotated by OnMessage receive different message types, respectively.

3.2 Error Codes

@ServerEndpoint ("/echo") public class Echoendpoint {@OnMessage public string OnMessage (string message,session sessio        N) {System.out.println ("Received:" + message);    return message+ "-" +session.getid (); } @OnMessage public String OnMessage2 (string message,session Session) {System.out.println ("Received:" + mes        SAGE);    Return message+ "# # #" +session.getid (); }}

Change the code to report a run-time exception.

javax.servlet.ServletException:javax.websocket.DeploymentException:Duplicate annotation

A message type that can only correspond to one onmessage method.

Reference Resources

Https://docs.oracle.com/javaee/7/tutorial/websocket005.htm

Conclusion: The message-related content is summarized by different stages of message processing. Next, we will discuss WebSocket related configuration information and error handling.

This article is from a "simple" blog, so be sure to keep this source http://dba10g.blog.51cto.com/764602/1855978

WebSocket Combat (2) Information processing send, receive and encode

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.