WebSocket使用sendObject(Object arg0)向页面方法发送对象

WebSocket接口中有一个直接发送对象给页面的方法:

voidjavax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0) throws IOException,EncodeException

如果直接使用

client.session.getBasicRemote().sendObject(obj);

就会出现以下错误:

javax.websocket.EncodeException: No encoder specified for object of class [class org.ywzn.po.Messagepojo]

解决的方法有一个,就是需要一个编码器,具体步骤如下:

 

1、自定义的一个普通Java实体类,这个没有什么特别,一些属性、set、get、toString方法而已

 

 
  1. package org.ywzn.po;

  2.  
  3. import java.io.Serializable;

  4.  
  5. /**

  6. * 发送给ActiveMQ的实体类

  7. *

  8. * @author 夏小雪 日期:2015年6月11日 时间:下午12:14:18

  9. */

  10. public class Messagepojo implements Serializable {

  11.  
  12. private static final long serialVersionUID = -6451812593150428369L;

  13.  
  14. private String sourse;// 信息来源

  15. private String messageType;// 消息类型

  16. private String msgContent;// 消息内容

  17. private String target;// 发送目的地

  18. private String infoSourceIP;// 信息来源ip

  19. private String createtime;// 消息保存时间

  20. private String otherContent;// 其他信息

  21.  
  22. public Messagepojo() {

  23. super();

  24. }

  25.  
  26. public Messagepojo(String sourse, String messageType, String msgContent,

  27. String target, String infoSourceIP, String createtime,

  28. String otherContent) {

  29. super();

  30. this.sourse = sourse;

  31. this.messageType = messageType;

  32. this.msgContent = msgContent;

  33. this.target = target;

  34. this.infoSourceIP = infoSourceIP;

  35. this.createtime = createtime;

  36. this.otherContent = otherContent;

  37. }

  38.  
  39. public String getSourse() {

  40. return sourse;

  41. }

  42.  
  43. public void setSourse(String sourse) {

  44. this.sourse = sourse;

  45. }

  46.  
  47. public String getMessageType() {

  48. return messageType;

  49. }

  50.  
  51. public void setMessageType(String messageType) {

  52. this.messageType = messageType;

  53. }

  54.  
  55. public String getMsgContent() {

  56. return msgContent;

  57. }

  58.  
  59. public void setMsgContent(String msgContent) {

  60. this.msgContent = msgContent;

  61. }

  62.  
  63. public String getTarget() {

  64. return target;

  65. }

  66.  
  67. public void setTarget(String target) {

  68. this.target = target;

  69. }

  70.  
  71. public String getInfoSourceIP() {

  72. return infoSourceIP;

  73. }

  74.  
  75. public void setInfoSourceIP(String infoSourceIP) {

  76. this.infoSourceIP = infoSourceIP;

  77. }

  78.  
  79. public String getCreatetime() {

  80. return createtime;

  81. }

  82.  
  83. public void setCreatetime(String createtime) {

  84. this.createtime = createtime;

  85. }

  86.  
  87. public String getOtherContent() {

  88. return otherContent;

  89. }

  90.  
  91. public void setOtherContent(String otherContent) {

  92. this.otherContent = otherContent;

  93. }

  94.  
  95. @Override

  96. public String toString() {

  97. return "Messagepojo [sourse=" + sourse + ", messageType=" + messageType

  98. + ", msgContent=" + msgContent + ", target=" + target

  99. + ", infoSourceIP=" + infoSourceIP + ", createtime="

  100. + createtime + ", otherContent=" + otherContent + "]";

  101. }

  102.  
  103. }


2、编写自己的解码器

 

在encode()的这个方法内,可以自定义要返回的值,这里我需要的是Java对象转成的Json格式字符串,用的是一个自己写的工具类,这个可以根据自己的需求自定义,这里只给各位做一个参考。

 

 
  1. package org.ywzn.websocket;

  2.  
  3. import javax.websocket.EncodeException;

  4. import javax.websocket.Encoder;

  5. import javax.websocket.EndpointConfig;

  6.  
  7. import org.ywzn.po.Messagepojo;

  8. import org.ywzn.util.Java2Json;

  9.  
  10. import com.sdicons.json.mapper.MapperException;

  11.  
  12. /**

  13. * definition for our encoder

  14. *

  15. * @编写人: 夏小雪 日期:2015年6月14日 时间:上午11:58:23

  16. */

  17. public class ServerEncoder implements Encoder.Text<Messagepojo> {

  18.  
  19. @Override

  20. public void destroy() {

  21. // TODO Auto-generated method stub

  22.  
  23. }

  24.  
  25. @Override

  26. public void init(EndpointConfig arg0) {

  27. // TODO Auto-generated method stub

  28.  
  29. }

  30.  
  31. @Override

  32. public String encode(Messagepojo messagepojo) throws EncodeException {

  33. try {

  34. return Java2Json.JavaToJson(messagepojo, false);

  35. } catch (MapperException e) {

  36. // TODO Auto-generated catch block

  37. e.printStackTrace();

  38. return null;

  39. }

  40. }

  41.  
  42. }


3、WebSocket的服务终端

 

重要的地方只有一个:

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

encoders加入了刚刚自定义的解码类,这样就可以直接使用client.session.getBasicRemote().sendObject(obj);传入对象了。

 

 

 
  1. package org.ywzn.websocket;

  2.  
  3. import java.io.IOException;

  4. import java.text.SimpleDateFormat;

  5. import java.util.Date;

  6. import java.util.HashMap;

  7. import java.util.Map;

  8. import java.util.concurrent.atomic.AtomicInteger;

  9.  
  10. import javax.websocket.EncodeException;

  11. import javax.websocket.EndpointConfig;

  12. import javax.websocket.OnClose;

  13. import javax.websocket.OnError;

  14. import javax.websocket.OnMessage;

  15. import javax.websocket.OnOpen;

  16. import javax.websocket.Session;

  17. import javax.websocket.server.ServerEndpoint;

  18.  
  19. import org.apache.commons.logging.Log;

  20. import org.apache.commons.logging.LogFactory;

  21. import org.ywzn.activemq.Sender;

  22. import org.ywzn.po.Messagepojo;

  23. import org.ywzn.util.Java2Json;

  24.  
  25. import com.sdicons.json.mapper.MapperException;

  26.  
  27. /**

  28. * 消息协查中心 WebSocket 消息推送服务类

  29. *

  30. * @author 夏小雪 日期:2015年6月10日 时间:上午9:48:59

  31. */

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

  33. public class NewsAnnotation {

  34.  
  35. private static final Log log = LogFactory.getLog(NewsAnnotation.class);

  36.  
  37. private static final String GUEST_PREFIX = "Guest";

  38. private static final AtomicInteger connectionIds = new AtomicInteger(0);

  39. private static final Map<String, Object> connections = new HashMap<String, Object>();

  40. private static final String[] GUESTNAME = { "高勇", "梁肇辉", "李燕",

  41. "梁晓晓", "蔡俊", "张新", "高帅", "夏小雪", "彭连英", "刘剑" };

  42. private String nickname;

  43. private Session session;

  44.  
  45. // 当前用户id

  46. private Integer id;

  47.  
  48. // private HttpSession httpSession;

  49.  
  50. public NewsAnnotation() {

  51. // nickname = GUEST_PREFIX + connectionIds.getAndIncrement();

  52. // int index = connectionIds.getAndIncrement();

  53. // if (index >= 8) {

  54. // connectionIds.set(0);

  55. // }

  56. // nickname = GUESTNAME[index];

  57. }

  58.  
  59. @OnOpen

  60. public void start(Session session, EndpointConfig config) {

  61. // Set<Entry<String, Object>> entrySet =

  62. // config.getUserProperties().entrySet();

  63. // for (Iterator<Entry<String, Object>> iterator = entrySet.iterator();

  64. // iterator.hasNext();) {

  65. // String key = iterator.next().getKey();

  66. // System.out.println("[EndpointConfig-->key]:" + key);

  67. // System.out.println("value-->" + config.getUserProperties().get(key));

  68. // PojoMethodMapping p =

  69. // (PojoMethodMapping)config.getUserProperties().get(key);

  70. // System.out.println("p.getWsPath()-->" + p.getWsPath());

  71. // }

  72. // String negotiatedSubprotocol = session.getNegotiatedSubprotocol();

  73. // System.out.println("[getAuthority]:" +

  74. // session.getRequestURI().getAuthority());

  75. // System.out.println("[getFragment]:" +

  76. // session.getRequestURI().getFragment());

  77. // System.out.println("[getPath]:" + session.getRequestURI().getPath());

  78. // System.out.println("[getPort]:" + session.getRequestURI().getPort());

  79. // System.out.println("[getQuery]:" +

  80. // session.getRequestURI().getQuery());

  81. // System.out.println("[getRawUserInfo]:" +

  82. // session.getRequestURI().getRawAuthority());

  83. // System.out.println("[getRawFragment]:" +

  84. // session.getRequestURI().getRawFragment());

  85. // System.out.println("[getHost]:" + session.getRequestURI().getHost());

  86. // System.out.println("[getRawUserInfo]:" +

  87. // session.getRequestURI().getRawUserInfo());

  88. // System.out.println("[getScheme]:" +

  89. // session.getRequestURI().getScheme());

  90. // System.out.println("[getSchemeSpecificPart]:" +

  91. // session.getRequestURI().getSchemeSpecificPart());

  92. // System.out.println("[getUserInfo]:" +

  93. // session.getRequestURI().getUserInfo());

  94. // System.out.println("[negotiatedSubprotocol]:" +

  95. // negotiatedSubprotocol);

  96. // Set<Entry<String, String>> entrySet =

  97. // session.getPathParameters().entrySet();

  98. // for(Iterator<Entry<String, String>> iter =

  99. // entrySet.iterator();iter.hasNext();){

  100. // System.out.println("[getKey]:" + iter.next().getKey());

  101. // }

  102. // System.out.println("[session.getProtocolVersion()]:" +

  103. // session.getProtocolVersion());

  104.  
  105. this.session = session;

  106. id = Integer.parseInt(this.session.getId());

  107. if (id > 8) {

  108. id = 0;

  109. }

  110. nickname = GUESTNAME[id];

  111. System.out.println("当前用户的ID是:" + id + "\n用户姓名是:" + nickname);

  112. connections.put(nickname, this);

  113. String message = String.format("* %s %s", nickname, "已经登录消息协查中心.");

  114. // 群发

  115. broadcast(message, "all");

  116. // 发送登录的消息给activemq

  117. Sender.sendMsg("login:" + nickname);

  118. }

  119.  
  120. @OnClose

  121. public void end() {

  122. System.out.println("消息中心连接关闭.");

  123. connections.remove(this);

  124. String message = String

  125. .format("* %s %s", nickname, "has disconnected.");

  126. // 群发

  127. // broadcast(message, "all");

  128. // 发送登录的消息给activemq

  129. // Sender.sendMsg("quit:" + nickname);

  130. }

  131.  
  132. /**

  133. * 消息发送触发方法

  134. *

  135. * @param message

  136. */

  137. @OnMessage

  138. public void incoming(String message) {

  139. System.out.println("Java收到了网页[" + this.nickname + "]的消息[message]:"

  140. + message);

  141. // Never trust the client

  142. String filteredMessage = String.format("%s: %s", nickname,

  143. HTMLFilter.filter(message.toString()));

  144.  
  145. // 发送登录的消息给activemq

  146. Messagepojo messagepojo = new Messagepojo(this.nickname, "用户对话",

  147. message, "all", this.id.toString(), new SimpleDateFormat(

  148. "yyyy-MM-dd hh:mm:ss").format(new Date()), "");

  149. try {

  150. String javaToJson = Java2Json.JavaToJson(messagepojo, false);

  151. System.out.println("发送信息:" + javaToJson);

  152. Sender.sendMsg("Message-->" + javaToJson);

  153. } catch (MapperException e) {

  154. // TODO Auto-generated catch block

  155. e.printStackTrace();

  156. }

  157. // Sender.sendMsg("sendMsg:" + message);

  158. // broadcast(filteredMessage, "all");

  159. }

  160.  
  161. @OnError

  162. public void one rror(Throwable t) throws Throwable {

  163. log.error("Chat Error: " + t.toString(), t);

  164. }

  165.  
  166. /**

  167. * 消息发送方法 author 夏小雪 日期:2015年6月10日 时间:上午9:49:45

  168. *

  169. * @param msg

  170. * 发送的内容

  171. * @param user

  172. * 发给指定的用户,如果要发给所有的则填""或"all"

  173. */

  174. private static void broadcast(String msg, String user) {

  175. // 是否群发

  176. if (user == null || "all".equals(user) || "".equals(user)) {

  177. sendAll(msg);

  178. } else {

  179. sendUser(msg, user);

  180. }

  181. }

  182.  
  183. /**

  184. * 向所有用户发送 author 夏小雪 日期:2015年6月10日 时间:上午9:50:34

  185. *

  186. * @param msg

  187. */

  188. public static void sendAll(String msg) {

  189. for (String key : connections.keySet()) {

  190. NewsAnnotation client = null;

  191. try {

  192. client = (NewsAnnotation) connections.get(key);

  193. synchronized (client) {

  194. if (client.session.isOpen()) { // 如果这个session是打开的

  195. client.session.getBasicRemote().sendText(msg);

  196. }

  197. }

  198. } catch (IOException e) {

  199. log.debug("Chat Error: Failed to send message to client", e);

  200. connections.remove(client);

  201. try {

  202. client.session.close();

  203. } catch (IOException e1) {

  204. // Ignore

  205. }

  206. String message = String.format("* %s %s", client.nickname,

  207. "has been disconnected.");

  208. // 群发

  209. broadcast(message, "all");

  210. }

  211. }

  212. }

  213.  
  214. /**

  215. * 向所有用户发送

  216. *

  217. * @编写人: 夏小雪 日期:2015年6月14日 时间:上午11:14:46

  218. * @param obj

  219. * 对象

  220. */

  221. public static void sendAll(Object obj) {

  222. for (String key : connections.keySet()) {

  223. NewsAnnotation client = null;

  224. try {

  225. client = (NewsAnnotation) connections.get(key);

  226. synchronized (client) {

  227. if (client.session.isOpen()) { // 如果这个session是打开的

  228. client.session.getBasicRemote().sendObject(obj);

  229. }

  230. }

  231. } catch (IOException e) {

  232. log.debug("Chat Error: Failed to send message to client", e);

  233. connections.remove(client);

  234. try {

  235. client.session.close();

  236. } catch (IOException e1) {

  237. // Ignore

  238. }

  239. String message = String.format("* %s %s", client.nickname,

  240. "has been disconnected.");

  241. // 群发

  242. broadcast(message, "all");

  243. } catch (EncodeException e) {

  244. // TODO Auto-generated catch block

  245. e.printStackTrace();

  246. }

  247. }

  248. }

  249.  
  250. /**

  251. * 向指定用户发送消息 author 夏小雪 日期:2015年6月10日 时间:上午9:50:45

  252. *

  253. * @param msg

  254. * 内容

  255. * @param user

  256. * 用户

  257. */

  258. public static void sendUser(String msg, String user) {

  259. // 获取要发送的用户

  260. NewsAnnotation c = (NewsAnnotation) connections.get(user);

  261. try {

  262. if (c != null) {

  263. c.session.getBasicRemote().sendText(msg);

  264. }

  265. } catch (IOException e) {

  266. log.debug("Chat Error: Failed to send message to client", e);

  267. connections.remove(c);

  268. try {

  269. c.session.close();

  270. } catch (IOException e1) {

  271. // Ignore

  272. }

  273. String message = String.format("* %s %s", c.nickname,

  274. "has been disconnected.");

  275. // 群发

  276. broadcast(message, "all");

  277. }

  278. }

  279. }


我这里已经搭建了WebSocket和ActiveMQ的框架,下面截图看下效果:

 

WebSocket使用sendObject(Object arg0)向页面方法发送对象

 

WebSocket使用sendObject(Object arg0)向页面方法发送对象

WebSocket使用sendObject(Object arg0)向页面方法发送对象

 

参考资料:

编码器的任务是将应用程序特定的数据转换成可传送到客户机端点格式。创建一个编码器,我们将要知道的一些接口,就像这样,我们不得不在创建解码器。

 

decoder.

Encoder The Encoder interface defines how developers can provide a way 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 way to convert a custom object into a binary message.
Encoder.BinaryStream<T> This interface may be implemented by encoding algorithms that want to write the encoded object to a binary stream.
Encoder.Text<T> This interface defines how to provide a way to convert a custom object into a text message.
Encoder.TextStream<T> This interface may be implemented by encoding algorithms that want to write the encoded object to a character stream.
上一篇:js中对String去空格


下一篇:恋爱论(转)