WebSocket sending an object to a page method using Javax.websocket.RemoteEndpoint.Basic.sendObject (Object arg0)

Source: Internet
Author: User
Tags log log sendmsg throwable

The WebSocket interface has a way to send objects directly to the page:

voidjavax. WebSocket. Remoteendpoint. BasicsendObject (Object arg0) throws IOException,encodeexception

If you directly use

Client.session.getBasicRemote (). SendObject (obj);

The following error will occur:

JAVAX.WEBSOCKET.ENCODEEXCEPTION:NO encoder specified for object of class [class Org.ywzn.po.Messagepojo]

One solution is to need an encoder, the following steps:


1, custom of a common Java entity class, this is nothing special, some properties, set, Get, ToString method only

Package Org.ywzn.po;import java.io.serializable;/** * sent to ACTIVEMQ entity class * * @author Summer Snow Date: June 11, 2015 time: PM 12:14:18 */publi C Class Messagepojo implements Serializable {private static final long Serialversionuid = -6451812593150428369l;private St Ring sourse;//Information Source private string messagetype;//message type private string msgcontent;//message content private string target;//send destination Priva Te string infosourceip;//information source ipprivate string createtime;//message save time private String othercontent;//other information public Messagepojo () {super ();} Public Messagepojo (String sourse, String messageType, String msgcontent,string target, String infosourceip, string create Time,string othercontent) {super (); this.sourse = Sourse;this.messagetype = Messagetype;this.msgcontent = msgContent; This.target = Target;this.infosourceip = Infosourceip;this.createtime = Createtime;this.othercontent = otherContent;} Public String Getsourse () {return sourse;} public void Setsourse (String sourse) {this.sourse = Sourse;} Public String Getmessagetype () {return messageType;} public void Setmessagetype (String messageType) {this.messagetype = MessageType;} Public String getmsgcontent () {return msgcontent;} public void Setmsgcontent (String msgcontent) {this.msgcontent = msgcontent;} Public String Gettarget () {return target;} public void Settarget (String target) {this.target = target;} Public String Getinfosourceip () {return INFOSOURCEIP;} public void Setinfosourceip (String infosourceip) {this.infosourceip = Infosourceip;} Public String Getcreatetime () {return createtime;} public void Setcreatetime (String createtime) {this.createtime = Createtime;} Public String getothercontent () {return othercontent;} public void Setothercontent (String othercontent) {this.othercontent = othercontent;} @Overridepublic String toString () {return "Messagepojo [sourse=" + Sourse + ", messagetype=" + messagetype+ ", msgcontent= "+ Msgcontent +", target= "+ target+", infosourceip= "+ Infosourceip +", createtime= "+ Createtime +", othercontent= " + Othercontent + "]";}}

2. Write your own decoder

In this method of encode (), you can customize the value to return, here I need is the Java object into the JSON format string, with a self-written tool class, this can be customized according to their own needs, here only to do a reference.

Package Org.ywzn.websocket;import Javax.websocket.encodeexception;import Javax.websocket.encoder;import Javax.websocket.endpointconfig;import Org.ywzn.po.messagepojo;import Org.ywzn.util.java2json;import com.sdicons.json.mapper.mapperexception;/** * Definition for US encoder *  * @ Writer: Summer Snow date: June 14, 2015 time: 11:58:23 */ public class Serverencoder implements encoder.text<messagepojo> {@Overridepublic void Destroy () {//TODO auto-generated method stub} @Overridepublic void Init (Endpointconfig arg0) {//TODO auto-generated method stub}@ Overridepublic String encode (Messagepojo Messagepojo) throws Encodeexception {try {return Java2json.javatojson ( Messagepojo, false);} catch (Mapperexception e) {//TODO auto-generated catch Blocke.printstacktrace (); return null;}}}

3, WebSocket service terminal

There is only one important place:

@ServerEndpoint (value = "/websocket/news", encoders = {Serverencoder.class})

Encoders added a newly-customized decoding class so that you can use the Client.session.getBasicRemote (). SendObject (obj) directly, and pass in the object.


Package Org.ywzn.websocket;import Java.io.ioexception;import Java.text.simpledateformat;import java.util.Date; Import Java.util.hashmap;import Java.util.map;import Java.util.concurrent.atomic.atomicinteger;import Javax.websocket.encodeexception;import Javax.websocket.endpointconfig;import Javax.websocket.OnClose;import Javax.websocket.onerror;import Javax.websocket.onmessage;import Javax.websocket.onopen;import Javax.websocket.session;import Javax.websocket.server.serverendpoint;import Org.apache.commons.logging.Log; Import Org.apache.commons.logging.logfactory;import Org.ywzn.activemq.sender;import Org.ywzn.po.Messagepojo; Import Org.ywzn.util.java2json;import com.sdicons.json.mapper.mapperexception;/** * Message Assistant Investigation Center WebSocket message Push Service class * * @ Author Summer snow Date: June 10, 2015 time: Morning 9:48:59 */@ServerEndpoint (value = "/websocket/news", encoders = {Serverencoder.class}) pub Lic class Newsannotation {private static final log log = Logfactory.getlog (newsannotation.class);p rivate static final Stri Ng Guest_prefIX = "Guest";p rivate static final Atomicinteger connectionids = new Atomicinteger (0);p rivate static final map<string, O bject> connections = new hashmap<string, object> ();p rivate static final string[] Guestname = {"Gaoyong", "fingerlings", "Li Yan", "Liang", "Cai Jun", "Zhang Xin", "Gao Shuai", "Summer Snow", "Penglianying", "Liu Jian"};p rivate String nickname;private Session session;//Current user idprivate Integer ID ;//Private HttpSession httpsession;public newsannotation () {//nickname = Guest_prefix + connectionids.getandincrement ( );//INT index = Connectionids.getandincrement ();/if (index >= 8) {//Connectionids.set (0);//}//nickname = Guestnam E[index];} @OnOpenpublic Void Start (session session, Endpointconfig Config) {//set<entry<string, object>> entryset =// Config.getuserproperties (). EntrySet ();//For (iterator<entry<string, object>> Iterator = Entryset.iterator ();//Iterator.hasnext ();) {//String key = Iterator.next (). GetKey ();//System.out.println ("[Endpointconfig-->key]:" + key);//SYSTEM.OUT.PRIntln ("value-->" + config.getuserproperties (). Get (key));//pojomethodmapping P =//(pojomethodmapping) Config.getuserproperties (). get (key);//System.out.println ("P.getwspath ()--" + P.getwspath ());//}//String Negotiatedsubprotocol = Session.getnegotiatedsubprotocol ();//System.out.println ("[Getauthority]:" +// Session.getrequesturi (). getauthority ());//System.out.println ("[Getfragment]:" +//Session.getrequesturi (). Getfragment ());//System.out.println ("[GetPath]:" + Session.getrequesturi (). GetPath ());//System.out.println ("[ Getport]: "+ Session.getrequesturi (). Getport ());//System.out.println (" [Getquery]: "+//Session.getrequesturi (). Getquery ());//System.out.println ("[Getrawuserinfo]:" +//Session.getrequesturi (). getrawauthority ());// System.out.println ("[Getrawfragment]:" +//Session.getrequesturi (). Getrawfragment ());//System.out.println ("[ GetHost]: "+ Session.getrequesturi (). GetHost ());//System.out.println (" [Getrawuserinfo]: "+//Session.getrequesturi (). Getrawuserinfo ());// System.out.println ("[Getscheme]:" +//Session.getrequesturi (). Getscheme ());//System.out.println ("[ Getschemespecificpart]: "+//Session.getrequesturi (). Getschemespecificpart ());//System.out.println (" [GetUserInfo ]: "+//Session.getrequesturi (). GetUserInfo ());//System.out.println (" [Negotiatedsubprotocol]: "+// NEGOTIATEDSUBPROTOCOL);//set<entry<string, string>> entryset =//session.getpathparameters (). EntrySet ( );//For (iterator<entry<string, string>> iter =//entryset.iterator (); Iter.hasnext ();) {// System.out.println ("[GetKey]:" + iter.next (). GetKey ());//}//System.out.println ("[Session.getprotocolversion ()]:" +//session.getprotocolversion ()); this.session = Session;id = Integer.parseint (This.session.getId ()); if (ID > 8) {ID = 0;} Nickname = Guestname[id]; SYSTEM.OUT.PRINTLN ("The ID of the current user is:" + ID + "\ nthe user name is:" + nickname); Connections.put (nickname, this); String message = String.Format ("*%s%s", nickname, "Already logged in Message Assistant Investigation Center."); /mass broadcast (message, "all");//Send login messages to actIvemqsender.sendmsg ("Login:" + nickname);} @OnClosepublic void End () {SYSTEM.OUT.PRINTLN ("Message Center connection closed."); Connections.remove (this); String message = String.Format ("*%s%s", nickname, "has disconnected."); /mass//broadcast (message, "all");//Send the login message to activemq//sender.sendmsg ("Quit:" + nickname);} /** * Message Sending Trigger Method * * @param message */@OnMessagepublic void incoming (String message) {System.out.println ("Java received Web page [" + Thi S.nickname + "] messages [message]:" + message ";//Never trust the clientstring filteredmessage = String.Format ("%s:%s ", nickname , Htmlfilter.filter (Message.tostring ()));//Send the login message to Activemqmessagepojo Messagepojo = new Messagepojo (This.nickname, "User dialog", message, "All", this.id.toString (), New SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"). Format (new Date ()), ""); try { String Javatojson = Java2json.javatojson (Messagepojo, false); SYSTEM.OUT.PRINTLN ("Send message:" + Javatojson); Sender.sendmsg ("message-->" + Javatojson);} catch (Mapperexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} // Sender.sendmsg ("sendmsg:" + message);//Broadcast (Filteredmessage, "All");} @OnErrorpublic void OnError (Throwable t) throws Throwable {log.error ("Chat error:" + t.tostring (), t);} /** * Message Sending method author Summer Snow date: June 10, 2015 time: Morning 9:49:45 * * @param msg * Content sent * @param user * Sent to the specified user, such as */private static void Broadcast (string msg, string user) {//whether mass if (user = = NULL | | "All". Equals (user) | | "". Equals (user) {Sendall (msg);} else {senduser (msg, user);}} /** * Send author to all users Summer Snow date: June 10, 2015 time: Morning 9:50:34 * * @param msg */public static void Sendall (String msg) {for (string Key:connections.keySet ()) {Newsannotation client = null;try {client = (newsannotation) connections.get (key); Synchronized (client) {if (Client.session.isOpen ()) {///If this session is open Client.session.getBasicRemote (). SendText (msg );}}} catch (IOException e) {log.debug ("Chat error:failed to send message to client", e); connections.remove (client); try {Client . Session.close ();} catch (IoexceptioN E1) {//Ignore}string message = String.Format ("*%s%s", Client.nickname, "has been disconnected."); /mass broadcast (message, "All");}}} /** * Send to all users * * @ Writer: Summer Snow date: June 14, 2015 time: Morning 11:14:46 * @param obj * object */public static void Sendall (object obj) {for (String Key:connections.keySet ()) {Newsannotation client = null;try {client = (newsannotation) connections.get (key); synchronized (client) {if (Client.session.isOpen ()) {//If the session is open Client.session.getBasicRemote (). SendObject (obj);}}} catch (IOException e) {log.debug ("Chat error:failed to send message to client", e); connections.remove (client); try {Client . Session.close ();} catch (IOException E1) {//Ignore}string message = String.Format ("*%s%s", Client.nickname, "has been disconnected."); /mass broadcast (message, "All");} catch (Encodeexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} /** * Send a message to a specified user author summer snow date: June 10, 2015 time: Morning 9:50:45 * * @param msg * content * @param user * Users */public static void Senduser (String msg, string user) {//Gets the user to send newsannotation c = (newsannotation) connections.get (US  ER); try {if (c! = null) {C.session.getbasicremote (). SendText (msg)}} catch (IOException e) {log.debug ("Chat error:failed To send a message to client ", e); Connections.remove (c); try {c.session.close ();} catch (IOException E1) {//Ignore}string Me Ssage = String.Format ("*%s%s", C.nickname, "has been disconnected."); /mass broadcast (message, "All");}}}

I have built a frame of websocket and activemq here, the following look at the effect:






Resources:

The task of the encoder is to convert application-specific data into a format that can be transferred to the client endpoint. To create an encoder, we're going to know some of the interfaces, just like this, we had to create a decoder.

Decoder.

Encoder The Encoder interface defines how developers can provide a-to-convert their custom objects into Web socket messages. The Encoder interface contains subinterfaces that allow encoding algorithms to encode custom objects To:text, binary data , character stream and write to an output stream.
Encoder.binary<t> This interface defines how to provide a-to convert a custom object into a binary message.
Encoder.binarystream<t> This interface is implemented by encoding algorithms, want to write, the encoded object to a binary stream.
Encoder.text<t> This interface defines how to provide a-to convert a custom object into a text message.
Encoder.textstream<t> This interface is implemented by encoding algorithms, want to write, the encoded object to a character stream.
-See more at:http://www.javabeat.net/encoder-websocket-in-javaee-7/#sthash. Fmbfmc2q.dpuf


Reference: http://www.javabeat.net/encoder-websocket-in-javaee-7/

WebSocket sending an object to a page method using Javax.websocket.RemoteEndpoint.Basic.sendObject (Object arg0)

Related Article

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.