websocket @ServerEndpoint(value = "/websocket/{ip}")详解

时间:2020-01-10
本文章向大家介绍websocket @ServerEndpoint(value = "/websocket/{ip}")详解,主要包括websocket @ServerEndpoint(value = "/websocket/{ip}")详解使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

WebSocket是JavaEE7新支持的:

    Javax.websocket.server包含注解,类,接口用于创建和配置服务端点

    Javax.websocket包则包含服务端点和客户断电公用的注解,类,接口,异常

    创建一个编程式的端点,需要继承Endpoint类,重写它的方法。

    创建一个注解式的端点,将自己的写的类以及类中的一些方法用前面提到的包中的注解装饰(@EndPoint,@OnOpen等等)。

编程式注解示例:

  1. @Component
  2. @ServerEndpoint(value = "/websocket/{ip}")
  3. public class MyWebSocket {
  4.  
  5. private static final Logger log = LoggerFactory.getLogger(MyWebSocket.class);
  6.  
  7. // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
  8. private static int onlineCount = 0;
  9.  
  10. // concurrent包的线程安全Map,用来存放每个客户端对应的MyWebSocket对象。
  11. private static ConcurrentHashMap<String, MyWebSocket> webSocketMap = new ConcurrentHashMap<String, MyWebSocket>();
  12.  
  13. // 与某个客户端的连接会话,需要通过它来给客户端发送数据
  14. private Session session;
  15.  
  16. private String ip; // 客户端ip
  17. public static final String ACTION_PRINT_ORDER = "printOrder";
  18. public static final String ACTION_SHOW_PRINT_EXPORT = "showPrintExport";
  19.  
  20. /**
  21. * 连接建立成功调用的方法
  22. */
  23. @OnOpen
  24. public void onOpen(Session session, @PathParam("ip") String ip) {
  25. this.session = session;
  26. this.ip = ip;
  27. webSocketMap.put(ip, this);
  28. addOnlineCount(); // 在线数加1
  29. // System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
  30. log.info("有新连接加入,ip:{}!当前在线人数为:{}", ip, getOnlineCount());
  31. ExportService es = BeanUtils.getBean(ExportService.class);
  32. List<String> list = es.listExportCodesByPrintIp(ip);
  33. ResponseData<String> rd = new ResponseData<String>();
  34. rd.setAction(MyWebSocket.ACTION_SHOW_PRINT_EXPORT);
  35. rd.setList(list);
  36. sendObject(rd);
  37. }
  38.  
  39. /**
  40. * 连接关闭调用的方法
  41. */
  42. @OnClose
  43. public void onClose(@PathParam("ip") String ip) {
  44. webSocketMap.remove(ip); // 从set中删除
  45. // Map<String, String> map = session.getPathParameters();
  46. // webSocketMap.remove(map.get("ip"));
  47. subOnlineCount(); // 在线数减1
  48. // System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
  49. log.info("websocket关闭,IP:{},当前在线人数为:{}", ip, getOnlineCount());
  50. }
  51.  
  52. /**
  53. * 收到客户端消息后调用的方法
  54. *
  55. * @param message
  56. * 客户端发送过来的消息
  57. */
  58. @OnMessage
  59. public void onMessage(String message, Session session) {
  60. // System.out.println("来自客户端的消息:" + message);
  61. log.debug("websocket来自客户端的消息:{}", message);
  62. OrderService os = BeanUtils.getBean(OrderService.class);
  63. OrderVo ov = os.getOrderDetailByOrderNo(message);
  64. // System.out.println(ov);
  65. ResponseData<OrderVo> rd = new ResponseData<OrderVo>();
  66. ArrayList<OrderVo> list = new ArrayList<OrderVo>();
  67. list.add(ov);
  68. rd.setAction(MyWebSocket.ACTION_PRINT_ORDER);
  69. rd.setList(list);
  70. sendObject(rd);
  71. // log.info("推送打印信息完成,单号:{}", ov.getOrderNo());
  72. }
  73.  
  74. /**
  75. * 发生错误时调用
  76. */
  77. @OnError
  78. public void onError(Session session, Throwable error) {
  79. // System.out.println("发生错误");
  80. log.error("webSocket发生错误!IP:{}", ip);
  81. error.printStackTrace();
  82. }
  83.  
  84. /**
  85. * 像当前客户端发送消息
  86. *
  87. * @param message
  88. * 字符串消息
  89. * @throws IOException
  90. */
  91. public void sendMessage(String message) {
  92. try {
  93. this.session.getBasicRemote().sendText(message);
  94. // this.session.getAsyncRemote().sendText(message);
  95. } catch (IOException e) {
  96. e.printStackTrace();
  97. log.error("发送数据错误,ip:{},msg:{}", ip, message);
  98. }
  99. }
  100.  
  101. /**
  102. * 向当前客户端发送对象
  103. *
  104. * @param obj
  105. * 所发送对象
  106. * @throws IOException
  107. */
  108. public void sendObject(Object obj) {
  109. ObjectMapper mapper = new ObjectMapper();
  110. mapper.setSerializationInclusion(Include.NON_NULL);
  111. String s = null;
  112. try {
  113. s = mapper.writeValueAsString(obj);
  114. } catch (JsonProcessingException e) {
  115. e.printStackTrace();
  116. log.error("转json错误!{}", obj);
  117. }
  118. this.sendMessage(s);
  119. }
  120.  
  121. /**
  122. * 群发自定义消息
  123. */
  124. public static void sendInfo(String message) {
  125. for (Entry<String, MyWebSocket> entry : webSocketMap.entrySet()) {
  126. MyWebSocket value = entry.getValue();
  127. value.sendMessage(message);
  128. }
  129. }
  130.  
  131. public static synchronized int getOnlineCount() {
  132. return onlineCount;
  133. }
  134.  
  135. public static synchronized void addOnlineCount() {
  136. MyWebSocket.onlineCount++;
  137. }
  138.  
  139. public static synchronized void subOnlineCount() {
  140. MyWebSocket.onlineCount--;
  141. }
  142.  
  143. public static ConcurrentHashMap<String, MyWebSocket> getWebSocketMap() {
  144. return webSocketMap;
  145. }
  146.  
  147. }

当创建好一个(服务)端点之后,将它以一个指定的URI发布到应用当中,这样远程客户端就能连接上它了。

Websocket(服务)端点以URI表述,有如下的访问方式:

ws://host:port/path?query

wss://host:port/path?query

注解详解:

@ServerEndPoint:

    RequiredElements :

        Value: URI映射

    OptionalElemens:

        subprotocols:

        decoders:解码器

        encoders:编码器

        configurator

建立连接相关:

Annotation

Event

Example

OnOpen

Connection opened

@OnOpen

Public void open(Sessionsession,

EndpointConfig conf) { }

OnMessage

Message received

@OnMessage

public void message(Sessionsession,

String msg) { }

OnError

Connection error

@OnError

public void error(Sessionsession,

Throwable error) { }

OnClose

Connection closed

@OnClose

public void close(Sessionsession,

CloseReason reason) { }

Session代表着服务端点与远程客户端点的一次会话。

容器会为每一个连接创建一个EndPoint的实例,需要利用实例变量来保存一些状态信息。

Session.getUserProperties提供了一个可编辑的map来保存properties,

例如,下面的端点在收到文本消息时,将前一次收到的消息回复给其他的端点

  1. @ServerEndpoint("/delayedecho")
  2.  
  3. public class DelayedEchoEndpoint
  4.  
  5. {
  6.  
  7. @OnOpen
  8.  
  9. public void open(Sessionsession)
  10.  
  11. {
  12.  
  13. session.getUserProperties().put("previousMsg", "");
  14.  
  15. }
  16.  
  17.  
  18.  
  19. @OnMessage
  20.  
  21. public void message(Session session, Stringmsg)
  22.  
  23. {
  24.  
  25.  
  26.  
  27. String prev= (String) session.getUserProperties().get("previousMsg");
  28.  
  29.  
  30.  
  31. session.getUserProperties().put("previousMsg",msg);
  32.  
  33. try {
  34.  
  35. session.getBasicRemote().sendText(prev);
  36.  
  37.  
  38.  
  39. } catch (IOException e){ ... }
  40.  
  41. }
  42.  
  43. }

发送、接收消息:

Websocketendpoint能够发送和接收文本、二进制消息,另外,也可以发送ping帧和接收pong 帧

发送消息:

Obtain the Session object from theconnection.

从连接中获得Session对象

Session对象是endPoint中那些被注解标注的方法中可得到的参数

当你的message作为另外的消息的响应

在@OnMessage标注的方法中,有session对象接收message

如果你必须主动发送message,需要在标注了@OnOpen的方法中将session对象作为实例变量保存

这样,你可以再其他方法中得到该session对象

1.Use the Session object to obtain aRemote Endpoint object.

通过Session对象获得Remoteendpoint对象

2.Use the RemoteEndpoint object to sendmessages to the peer.

利用RemoteEndpoint对象来发送message

代码示例:

@ServerEndpoint("/echoall")

public class EchoAllEndpoint

{

@OnMessage

public void onMessage(Session session, Stringmsg)

{

try {

for (Session sess :session.getOpenSessions())

{

if (sess.isOpen())

sess.getBasicRemote().sendText(msg);

}

catch (IOExceptione) { ... }

}

}

接收消息

OnMessage注解指定方法来处理接收的messages

在一个端点类中,至多可以为三个方法标注@OnMessage注解

消息类型分别为:text、binary、pong。

 

我们查看一下ServerEndpoint类源码:

  1. @Retention(value = RetentionPolicy.RUNTIME)
  2. @Target(value = {ElementType.TYPE})
  3. public @interface ServerEndpoint {
  4.  
  5. public String value();
  6.  
  7. public String[] subprotocols() default {};
  8.  
  9. public Class<? extends Decoder>[] decoders() default {};
  10.  
  11. public Class<? extends Encoder>[] encoders() default {};
  12.  
  13. public Class<? extends ServerEndpointConfig.Configurator> configurator() default ServerEndpointConfig.Configurator.class;

Encoders and Decoders(编码器和解码器):

WebSocket Api 提供了encoders 和 decoders用于 Websocket Messages 与传统java 类型之间的转换

An encoder takes a Java object and produces a representation that can be transmitted as a WebSocket message;

编码器输入java对象,生成一种表现形式,能够被转换成Websocket message

for example, encoders typically produce JSON, XML, or binary representations.

例如:编码器通常生成json、XML、二进制三种表现形式

A decoder performs the reverse function; it reads a WebSocket message and creates a Java object.

解码器执行相反的方法,它读入Websocket消息,然后输出java对象

编码器编码:

looks for an encoder that matches your type and uses it to convert the object to a WebSocket message.

利用RemoteEndpoint.Basic 或者RemoteEndpoint.Async的sendObject(Object data)方法将对象作为消息发送,容器寻找一个符合此对象的编码器,

利用此编码器将此对象转换成Websocket message

代码示例:可以指定为自己的一个消息对象

  1. package com.zlxls.information;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.common.model.SocketMsg;
  5. import javax.websocket.EncodeException;
  6. import javax.websocket.Encoder;
  7. import javax.websocket.EndpointConfig;
  8.  
  9. /**
  10. * 配置WebSocket解码器,用于发送请求的时候可以发送Object对象,实则是json数据
  11. * sendObject()
  12. * @ClassNmae:ServerEncoder
  13. * @author zlx-雄雄
  14. * @date 2017-11-3 15:47:13
  15. *
  16. */
  17. public class ServerEncoder implements Encoder.Text<SocketMsg> {
  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(SocketMsg socketMsg) throws EncodeException {
  33. try {
  34. return JSON.toJSONString(socketMsg);
  35. } catch (Exception e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. return "";
  39. }
  40. }
  41.  
  42. }

Then, add the encodersparameter to the ServerEndpointannotation as follows:

@ServerEndpoint(

value = "/myendpoint",

encoders = { ServerEncoder.class, ServerEncoder1.class }

)

解码器解码:

Decoder.Binary<T>for binary messages

These interfaces specify the willDecode and decode methods.

the container calls the method annotated with @OnMessage that takes your custom Java type as a parameter if this method exists.

  1. package com.zlxls.information;
  2.  
  3. import com.common.model.SocketMsg;
  4. import javax.websocket.DecodeException;
  5. import javax.websocket.Decoder;
  6. import javax.websocket.EndpointConfig;
  7. /**
  8. * 解码器执,它读入Websocket消息,然后输出java对象
  9. * @ClassNmae:ServerDecoder
  10. * @author zlx-雄雄
  11. * @date 2017-11-11 9:12:09
  12. *
  13. */
  14. public class ServerDecoder implements Decoder.Text<SocketMsg>{
  15.  
  16. @Override
  17. public void init(EndpointConfig ec){}
  18.  
  19. @Override
  20. public void destroy(){}
  21.  
  22. @Override
  23. public SocketMsg decode(String string) throws DecodeException{
  24. // Read message...
  25. return new SocketMsg();
  26. }
  27.  
  28. @Override
  29. public boolean willDecode(String string){
  30. // Determine if the message can be converted into either a
  31. // MessageA object or a MessageB object...
  32. return false;
  33. }
  34. }

Then, add the decoderparameter to the ServerEndpointannotation as follows:

@ServerEndpoint(

value = "/myendpoint",

encoders = { ServerEncoder.class, ServerEncoder1.class },

decoders = {ServerDecoder.class }

)

处理错误:

To designate a method that handles errors in an annotated WebSocket endpoint, decorate it with @OnError:

  1. /**
  2. * 发生错误是调用方法
  3. * @param t
  4. * @throws Throwable
  5. */
  6. @OnError
  7. public void onError(Throwable t) throws Throwable {
  8. System.out.println("错误: " + t.toString());
  9. }

为一个注解式的端点指定一个处理error的方法,为此方法加上@OnError注解:

This method is invoked when there are connection problems, runtime errors from message handlers, or conversion errors when decoding messages.

 

当出现连接错误,运行时错误或者解码时转换错误,该方法才会被调用

指定端点配置类:

The Java API for WebSocket enables you to configure how the container creates server endpoint instances.

Websocket的api允许配置容器合适创建server endpoint 实例

You can provide custom endpoint configuration logic to:

Access the details of the initial HTTP request for a WebSocket connection

Perform custom checks on the OriginHTTP header

Modify the WebSocket handshake response

Choose a WebSocket subprotocol from those requested by the client

Control the instantiation and initialization of endpoint instances

To provide custom endpoint configuration logic, you extend the ServerEndpointConfig.Configurator class and override some of its methods.

继承ServerEndpointConfig.Configurator 类并重写一些方法,来完成custom endpoint configuration 的逻辑代码

In the endpoint class, you specify the configurator class using the configurator parameter of the ServerEndpoint annotation.

代码示例:

  1. package com.zlxls.information;
  2.  
  3. import javax.servlet.http.HttpSession;
  4. import javax.websocket.HandshakeResponse;
  5. import javax.websocket.server.HandshakeRequest;
  6. import javax.websocket.server.ServerEndpointConfig;
  7. import javax.websocket.server.ServerEndpointConfig.Configurator;
  8. /**
  9. * 由于websocket的协议与Http协议是不同的,
  10. * 所以造成了无法直接拿到session。
  11. * 但是问题总是要解决的,不然这个websocket协议所用的场景也就没了
  12. * 重写modifyHandshake,HandshakeRequest request可以获取httpSession
  13. * @ClassNmae:GetHttpSessionConfigurator
  14. * @author zlx-雄雄
  15. * @date 2017-11-3 15:47:13
  16. *
  17. */
  18. public class GetHttpSessionConfigurator extends Configurator{
  19. @Override
  20. public void modifyHandshake(ServerEndpointConfig sec,HandshakeRequest request, HandshakeResponse response) {
  21.  
  22. HttpSession httpSession=(HttpSession) request.getHttpSession();
  23.  
  24. sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
  25.  
  26. }
  27. }
  1. @OnOpen
  2. public void open(Session s, EndpointConfig conf){
  3.  
  4. HandshakeRequest req = (HandshakeRequest) conf.getUserProperties().get("sessionKey");
  5.  
  6. }

@ServerEndpoint(

value = "/myendpoint",

configurator=GetHttpSessionConfigurator.class

)

不过要特别说一句:

HandshakeRequest req = (HandshakeRequest) conf.getUserProperties().get("sessionKey");  目前获取到的是空值。会报错:java.lang.NullPointerException,这个错误信息,大家最熟悉不过了。

原因是:请求头里面并没有把相关的信息带上

这里就需要实现一个监听,作用很明显:将所有request请求都携带上httpSession,这样就可以正常访问了

说明:注解非常简单可以直接使用注解@WebListener,也可以再web.xml配置监听

    1. package com.zlxls.information;
    2.  
    3. import javax.servlet.ServletRequestEvent;
    4. import javax.servlet.ServletRequestListener;
    5. import javax.servlet.annotation.WebListener;
    6. import javax.servlet.http.HttpServletRequest;
    7.  
    8. /**
    9. * http://www.cnblogs.com/zhuxiaojie/p/6238826.html
    10. * 配置监听器,将所有request请求都携带上httpSession
    11. * 用于webSocket取Session
    12. * @ClassNmae:RequestListener
    13. * @author zlx-雄雄
    14. * @date 2017-11-4 11:27:33
    15. *
    16. */
    17. @WebListener
    18. public class RequestListener implements ServletRequestListener {
    19. @Override
    20. public void requestInitialized(ServletRequestEvent sre) {
    21.  
    22. //将所有request请求都携带上httpSession
    23. ((HttpServletRequest) sre.getServletRequest()).getSession();
    24.  
    25. }
    26. public RequestListener() {}
    27.  
    28. @Override
    29. public void requestDestroyed(ServletRequestEvent arg0) {}
    30. }


$flag 上一页 下一页