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. import java.io.Serializable;

  3. /**

  4. * 发送给ActiveMQ的实体类

  5. *

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

  7. */

  8. public class Messagepojo implements Serializable {

  9. private static final long serialVersionUID = -6451812593150428369L;

  10. private String sourse;// 信息来源

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

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

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

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

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

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

  17. public Messagepojo() {

  18. super();

  19. }

  20. public Messagepojo(String sourse, String messageType, String msgContent,

  21. String target, String infoSourceIP, String createtime,

  22. String otherContent) {

  23. super();

  24. this.sourse = sourse;

  25. this.messageType = messageType;

  26. this.msgContent = msgContent;

  27. this.target = target;

  28. this.infoSourceIP = infoSourceIP;

  29. this.createtime = createtime;

  30. this.otherContent = otherContent;

  31. }

  32. public String getSourse() {

  33. return sourse;

  34. }

  35. public void setSourse(String sourse) {

  36. this.sourse = sourse;

  37. }

  38. public String getMessageType() {

  39. return messageType;

  40. }

  41. public void setMessageType(String messageType) {

  42. this.messageType = messageType;

  43. }

  44. public String getMsgContent() {

  45. return msgContent;

  46. }

  47. public void setMsgContent(String msgContent) {

  48. this.msgContent = msgContent;

  49. }

  50. public String getTarget() {

  51. return target;

  52. }

  53. public void setTarget(String target) {

  54. this.target = target;

  55. }

  56. public String getInfoSourceIP() {

  57. return infoSourceIP;

  58. }

  59. public void setInfoSourceIP(String infoSourceIP) {

  60. this.infoSourceIP = infoSourceIP;

  61. }

  62. public String getCreatetime() {

  63. return createtime;

  64. }

  65. public void setCreatetime(String createtime) {

  66. this.createtime = createtime;

  67. }

  68. public String getOtherContent() {

  69. return otherContent;

  70. }

  71. public void setOtherContent(String otherContent) {

  72. this.otherContent = otherContent;

  73. }

  74. @Override

  75. public String toString() {

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

  77. + ", msgContent=" + msgContent + ", target=" + target

  78. + ", infoSourceIP=" + infoSourceIP + ", createtime="

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

  80. }

  81. }

2、编写自己的解码器

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

  1. package org.ywzn.websocket;

  2. import javax.websocket.EncodeException;

  3. import javax.websocket.Encoder;

  4. import javax.websocket.EndpointConfig;

  5. import org.ywzn.po.Messagepojo;

  6. import org.ywzn.util.Java2Json;

  7. import com.sdicons.json.mapper.MapperException;

  8. /**

  9. * definition for our encoder

  10. *

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

  12. */

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

  14. @Override

  15. public void destroy() {

  16. // TODO Auto-generated method stub

  17. }

  18. @Override

  19. public void init(EndpointConfig arg0) {

  20. // TODO Auto-generated method stub

  21. }

  22. @Override

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

  24. try {

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

  26. } catch (MapperException e) {

  27. // TODO Auto-generated catch block

  28. e.printStackTrace();

  29. return null;

  30. }

  31. }

  32. }

3、WebSocket的服务终端

重要的地方只有一个:

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

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

  1. package org.ywzn.websocket;

  2. import java.io.IOException;

  3. import java.text.SimpleDateFormat;

  4. import java.util.Date;

  5. import java.util.HashMap;

  6. import java.util.Map;

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

  8. import javax.websocket.EncodeException;

  9. import javax.websocket.EndpointConfig;

  10. import javax.websocket.OnClose;

  11. import javax.websocket.OnError;

  12. import javax.websocket.OnMessage;

  13. import javax.websocket.OnOpen;

  14. import javax.websocket.Session;

  15. import javax.websocket.server.ServerEndpoint;

  16. import org.apache.commons.logging.Log;

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

  18. import org.ywzn.activemq.Sender;

  19. import org.ywzn.po.Messagepojo;

  20. import org.ywzn.util.Java2Json;

  21. import com.sdicons.json.mapper.MapperException;

  22. /**

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

  24. *

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

  26. */

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

  28. public class NewsAnnotation {

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

  30. private static final String GUEST_PREFIX = "Guest";

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

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

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

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

  35. private String nickname;

  36. private Session session;

  37. // 当前用户id

  38. private Integer id;

  39. // private HttpSession httpSession;

  40. public NewsAnnotation() {

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

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

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

  44. // connectionIds.set(0);

  45. // }

  46. // nickname = GUESTNAME[index];

  47. }

  48. @OnOpen

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

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

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

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

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

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

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

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

  57. // PojoMethodMapping p =

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

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

  60. // }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  84. // negotiatedSubprotocol);

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

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

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

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

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

  90. // }

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

  92. // session.getProtocolVersion());

  93. this.session = session;

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

  95. if (id > 8) {

  96. id = 0;

  97. }

  98. nickname = GUESTNAME[id];

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

  100. connections.put(nickname, this);

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

  102. // 群发

  103. broadcast(message, "all");

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

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

  106. }

  107. @OnClose

  108. public void end() {

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

  110. connections.remove(this);

  111. String message = String

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

  113. // 群发

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

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

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

  117. }

  118. /**

  119. * 消息发送触发方法

  120. *

  121. * @param message

  122. */

  123. @OnMessage

  124. public void incoming(String message) {

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

  126. + message);

  127. // Never trust the client

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

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

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

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

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

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

  134. try {

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

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

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

  138. } catch (MapperException e) {

  139. // TODO Auto-generated catch block

  140. e.printStackTrace();

  141. }

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

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

  144. }

  145. @OnError

  146. public void onError(Throwable t) throws Throwable {

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

  148. }

  149. /**

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

  151. *

  152. * @param msg

  153. * 发送的内容

  154. * @param user

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

  156. */

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

  158. // 是否群发

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

  160. sendAll(msg);

  161. } else {

  162. sendUser(msg, user);

  163. }

  164. }

  165. /**

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

  167. *

  168. * @param msg

  169. */

  170. public static void sendAll(String msg) {

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

  172. NewsAnnotation client = null;

  173. try {

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

  175. synchronized (client) {

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

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

  178. }

  179. }

  180. } catch (IOException e) {

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

  182. connections.remove(client);

  183. try {

  184. client.session.close();

  185. } catch (IOException e1) {

  186. // Ignore

  187. }

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

  189. "has been disconnected.");

  190. // 群发

  191. broadcast(message, "all");

  192. }

  193. }

  194. }

  195. /**

  196. * 向所有用户发送

  197. *

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

  199. * @param obj

  200. * 对象

  201. */

  202. public static void sendAll(Object obj) {

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

  204. NewsAnnotation client = null;

  205. try {

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

  207. synchronized (client) {

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

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

  210. }

  211. }

  212. } catch (IOException e) {

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

  214. connections.remove(client);

  215. try {

  216. client.session.close();

  217. } catch (IOException e1) {

  218. // Ignore

  219. }

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

  221. "has been disconnected.");

  222. // 群发

  223. broadcast(message, "all");

  224. } catch (EncodeException e) {

  225. // TODO Auto-generated catch block

  226. e.printStackTrace();

  227. }

  228. }

  229. }

  230. /**

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

  232. *

  233. * @param msg

  234. * 内容

  235. * @param user

  236. * 用户

  237. */

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

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

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

  241. try {

  242. if (c != null) {

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

  244. }

  245. } catch (IOException e) {

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

  247. connections.remove(c);

  248. try {

  249. c.session.close();

  250. } catch (IOException e1) {

  251. // Ignore

  252. }

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

  254. "has been disconnected.");

  255. // 群发

  256. broadcast(message, "all");

  257. }

  258. }

  259. }

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

参考资料:

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

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.

WebSocket使用javax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0)向页面方法发送对象相关推荐

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

    WebSocket接口中有一个直接发送对象给页面的方法: voidjavax.websocket.RemoteEndpoint.Basic.sendObject(Object arg0) throws ...

  2. Object类中有哪些方法

    2019独角兽企业重金招聘Python工程师标准>>> Object类中的方法介绍 类Object是类层次结构的根类,每一个类都使用Object作为超类,所有对象(包括数组)都实现这 ...

  3. javax.websocket 使用指南

    除了https://blog.csdn.net/u011556070/article/details/105844786 的建立ws server方法之外这里再收录记载一种JSR356的方法javax ...

  4. javax.websocket.DeploymentException: The path [webScoketServiceBaidu/{appID}] is not valid.

    错误提示: javax.servlet.ServletException: javax.websocket.DeploymentException: The path [webScoketServic ...

  5. Spring Boot加入websocket后,单元测试报错(javax.websocket.server.ServerContainer not available)

    错误提示: Caused by: java.lang.IllegalStateException: javax.websocket.server.ServerContainer not availab ...

  6. Caused by: java.lang.IllegalStateException: javax.websocket.server.ServerContainer not available

    websocket导致spring boot 项目单元测试启动失败的问题解决 在单元测试时,项目启动报错 Caused by: java.lang.IllegalStateException: jav ...

  7. webSocket整理(二)--webSocket的模拟qq聊天案例

    一 前言 前面一篇大致讲解了webSocket的定义以及配置,那么这一篇通过简单案例对webSocket更好的理解与使用.使用的是spring-servlet-webSocket的整合形式.因为这里主 ...

  8. websocket之一:websocket简介

    Websocket websocket为一次HTTP握手后,后续通讯为tcp协议的通讯方式. WebSocket 使用一种被称作"Upgrade handshake(升级握手)"的 ...

  9. java websocket原理_Java WebSocket基本原理

    WebSocket协议介绍 WebSocket协议是一个网络协议,允许两个相连的端在一个单一TCP连接上进行全双工消息通信. 在WebSocket的场景中,连接通过HTTP和WebSocket端点交互 ...

最新文章

  1. C++ list 的使用
  2. WPF/Silverlight Undo/Redo框架
  3. java中多叉树(tree)的生成与显示
  4. Vue.js 2.5 发布,而这个会玩的团队已经自研出用 Vue 开发小程序的框架了
  5. 中国银行业100强名单发布
  6. HTML 拾色器 桌面取色器
  7. HTML5网页设计基础——播放器图标
  8. 其他计算机才能打印,关于HPM126A打印机共享问题-共享之后主机得打印一次后其他电脑才能打印...
  9. 新的开始-轩宇的c++学习之路
  10. OC 建议实现类似淘宝的物流步骤视图
  11. 计算机系学霸情书表白,大学生情书:各专业学霸的表白让人大开眼界,网友:果然要多读书...
  12. python空气质量指数计算_Python入门案例(八):空气质量指数(AQI)计算
  13. 拉里•埃里森和他的Oracle公司
  14. Task 3: Subword Models (附代码)(Stanford CS224N NLP with Deep Learning Winter 2019)
  15. [原]领带打法-半温莎结
  16. 不被多数人知道但却超好的东东
  17. 图文手把手教程--ESP32 MQTT连接阿里云生活物联网平台
  18. 基于SpringBoot的中医诊疗平台的设计与实现
  19. 商业转战短视频平台,浅看抖音的品牌营销特点
  20. Android逆向移花接木之添加AlertDialog

热门文章

  1. 一分钟带你打开TikTok直播的世界?
  2. Leetcode每日一题:110.balanced-binary-tree(平衡二叉树)
  3. 列表的修改,复制,遍历,嵌套和查询
  4. 数学建模3 插值算法
  5. SpringBoot指南(五)——拦截器、原生组件
  6. 【译】在设计表单的时候应该注意的八点
  7. 转载:linux驱动层到应用层的重要接口sys文件系统---/sys目录详解
  8. Linux学习总结(四十四)lnmp之php-fpm相关配置
  9. 教你用命令行扩展VHD的大小
  10. python logging默认情况下打印_python logging日志打印过程解析