首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

websocket @ServerEndpoint注解说明

  • 25-02-22 06:00
  • 2942
  • 13679
blog.csdn.net

首先我们查看一下ServerEndpoint类源码:

  1. @Retention(value = RetentionPolicy.RUNTIME)
  2. @Target(value = {ElementType.TYPE})
  3. public @interface ServerEndpoint {
  4. public String value();
  5. public String[] subprotocols() default {};
  6. public Class[] decoders() default {};
  7. public Class[] encoders() default {};
  8. public Class configurator() default ServerEndpointConfig.Configurator.class;
  9. }

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. import com.alibaba.fastjson.JSON;
  3. import com.common.model.SocketMsg;
  4. import javax.websocket.EncodeException;
  5. import javax.websocket.Encoder;
  6. import javax.websocket.EndpointConfig;
  7. /**
  8. * 配置WebSocket解码器,用于发送请求的时候可以发送Object对象,实则是json数据
  9. * sendObject()
  10. * @ClassNmae:ServerEncoder
  11. * @author zlx-雄雄
  12. * @date 2017-11-3 15:47:13
  13. *
  14. */
  15. public class ServerEncoder implements Encoder.Text<SocketMsg> {
  16. @Override
  17. public void destroy() {
  18. // TODO Auto-generated method stub
  19. }
  20. @Override
  21. public void init(EndpointConfig arg0) {
  22. // TODO Auto-generated method stub
  23. }
  24. @Override
  25. public String encode(SocketMsg socketMsg) throws EncodeException {
  26. try {
  27. return JSON.toJSONString(socketMsg);
  28. } catch (Exception e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. return "";
  32. }
  33. }
  34. }

Then, add the encodersparameter to the ServerEndpointannotation as follows:

@ServerEndpoint(

value = "/myendpoint",

encoders = { ServerEncoder.class, ServerEncoder1.class }

)

解码器解码:

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

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

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


文章知识点与官方知识档案匹配,可进一步学习相关知识
网络技能树首页概览45702 人正在系统学习中
注:本文转载自blog.csdn.net的生命无须向死而生的文章"https://blog.csdn.net/zlxls/article/details/78504591/"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top