java websocket @ServerEndpoint注解说明
http://www.blogjava.net/qbna350816/archive/2016/07/24/431302.html
https://segmentfault.com/q/1010000004955225
https://www.cnblogs.com/interdrp/p/4091056.html
框架是workerman
socket.io
使用四种框架分别实现百万websocket常连接的服务器
首先我们查看一下ServerEndpoint类源码:
- @Retention(value = RetentionPolicy.RUNTIME)
- @Target(value = {ElementType.TYPE})
- public @interface ServerEndpoint {
- public String value();
- public String[] subprotocols() default {};
- public Class<? extends Decoder>[] decoders() default {};
- public Class<? extends Encoder>[] encoders() default {};
- 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
代码示例:可以指定为自己的一个消息对象
- package com.zlxls.information;
- import com.alibaba.fastjson.JSON;
- import com.common.model.SocketMsg;
- import javax.websocket.EncodeException;
- import javax.websocket.Encoder;
- import javax.websocket.EndpointConfig;
- /**
- * 配置WebSocket解码器,用于发送请求的时候可以发送Object对象,实则是json数据
- * sendObject()
- * @ClassNmae:ServerEncoder
- * @author zlx-雄雄
- * @date 2017-11-3 15:47:13
- *
- */
- public class ServerEncoder implements Encoder.Text<SocketMsg> {
- @Override
- public void destroy() {
- // TODO Auto-generated method stub
- }
- @Override
- public void init(EndpointConfig arg0) {
- // TODO Auto-generated method stub
- }
- @Override
- public String encode(SocketMsg socketMsg) throws EncodeException {
- try {
- return JSON.toJSONString(socketMsg);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return "";
- }
- }
- }
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.
- package com.zlxls.information;
- import com.common.model.SocketMsg;
- import javax.websocket.DecodeException;
- import javax.websocket.Decoder;
- import javax.websocket.EndpointConfig;
- /**
- * 解码器执,它读入Websocket消息,然后输出java对象
- * @ClassNmae:ServerDecoder
- * @author zlx-雄雄
- * @date 2017-11-11 9:12:09
- *
- */
- public class ServerDecoder implements Decoder.Text<SocketMsg>{
- @Override
- public void init(EndpointConfig ec){}
- @Override
- public void destroy(){}
- @Override
- public SocketMsg decode(String string) throws DecodeException{
- // Read message...
- return new SocketMsg();
- }
- @Override
- public boolean willDecode(String string){
- // Determine if the message can be converted into either a
- // MessageA object or a MessageB object...
- return false;
- }
- }
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:
- /**
- * 发生错误是调用方法
- * @param t
- * @throws Throwable
- */
- @OnError
- public void onError(Throwable t) throws Throwable {
- System.out.println("错误: " + t.toString());
- }
为一个注解式的端点指定一个处理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.
代码示例:
- package com.zlxls.information;
- import javax.servlet.http.HttpSession;
- import javax.websocket.HandshakeResponse;
- import javax.websocket.server.HandshakeRequest;
- import javax.websocket.server.ServerEndpointConfig;
- import javax.websocket.server.ServerEndpointConfig.Configurator;
- /**
- * 由于websocket的协议与Http协议是不同的,
- * 所以造成了无法直接拿到session。
- * 但是问题总是要解决的,不然这个websocket协议所用的场景也就没了
- * 重写modifyHandshake,HandshakeRequest request可以获取httpSession
- * @ClassNmae:GetHttpSessionConfigurator
- * @author zlx-雄雄
- * @date 2017-11-3 15:47:13
- *
- */
- public class GetHttpSessionConfigurator extends Configurator{
- @Override
- public void modifyHandshake(ServerEndpointConfig sec,HandshakeRequest request, HandshakeResponse response) {
- HttpSession httpSession=(HttpSession) request.getHttpSession();
- sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
- }
- }
- @OnOpen
- public void open(Session s, EndpointConfig conf){
- HandshakeRequest req = (HandshakeRequest) conf.getUserProperties().get("sessionKey");
- }
@ServerEndpoint(
value = "/myendpoint",
configurator=GetHttpSessionConfigurator.class
)
不过要特别说一句:
HandshakeRequest req = (HandshakeRequest) conf.getUserProperties().get("sessionKey"); 目前获取到的是空值。会报错:java.lang.NullPointerException,这个错误信息,大家最熟悉不过了。
原因是:请求头里面并没有把相关的信息带上
这里就需要实现一个监听,作用很明显:将所有request请求都携带上httpSession,这样就可以正常访问了
说明:注解非常简单可以直接使用注解@WebListener,也可以再web.xml配置监听
- package com.zlxls.information;
- import javax.servlet.ServletRequestEvent;
- import javax.servlet.ServletRequestListener;
- import javax.servlet.annotation.WebListener;
- import javax.servlet.http.HttpServletRequest;
- /**
- * http://www.cnblogs.com/zhuxiaojie/p/6238826.html
- * 配置监听器,将所有request请求都携带上httpSession
- * 用于webSocket取Session
- * @ClassNmae:RequestListener
- * @author zlx-雄雄
- * @date 2017-11-4 11:27:33
- *
- */
- @WebListener
- public class RequestListener implements ServletRequestListener {
- @Override
- public void requestInitialized(ServletRequestEvent sre) {
- //将所有request请求都携带上httpSession
- ((HttpServletRequest) sre.getServletRequest()).getSession();
- }
- public RequestListener() {}
- @Override
- public void requestDestroyed(ServletRequestEvent arg0) {}
- }
java websocket @ServerEndpoint注解说明的更多相关文章
- java websocket学习
引言: websocket,webservice傻傻分不清楚,都觉得是很高深的东西,理解中的webservice是一种协议,通信协议,类似http协议的那种,比如使用webservice协议调后台接口 ...
- java websocket 简单使用【案例】
现很多网站为了实现即时通讯,所用的技术都是轮询(polling).轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发 出HTTP request,然后由服务器返回最新的数据给客服端的浏览器.这种 ...
- Websocket @serverendpoint 404
今天写一个前后端交互的websocket , 本来写着挺顺利的,但测试的时候蒙了,前端websocket发的连接请求竟然连接不上 返回状态Status 报了个404 ,然后看后台onError方法也没 ...
- Java WebSocket实现简易聊天室
一.Socket简介 Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求.Socket的英文原义是“孔”或“插座”,作为UNI ...
- java中的注解(Annotation)
转载:https://segmentfault.com/a/1190000007623013 简介 注解,java中提供了一种原程序中的元素关联任何信息.任何元素的途径的途径和方法. 注解是那些插入到 ...
- java @param参数注解
注解,@param是参数的解释.如/***@param s 这里表示对s的文字说明,描述 */ public void aa(String s){}一般java中@表示注解,解释一个方法,类,属性的作 ...
- JAVA高级特性 - 注解
注解是插入到代码中用于某种工具处理的标签.这些标签可以在源码层次上进行操作,或者可以处理编译器将其纳入到注解类文件中. 注解不会改变对程序的编译方式.Java编译器会对包含注解和不包含注解的代码生成相 ...
- 使用Jetty搭建Java Websocket Server,实现图像传输
https://my.oschina.net/yushulx/blog/298140 How to Implement a Java WebSocket Server for Image Transm ...
- java中的注解总结
1. 什么是注解 注解是java5引入的特性,在代码中插入一种注释化的信息,用于对代码进行说明,可以对包.类.接口.字段.方法参数.局部变量等进行注解.注解也叫元数据(meta data).这些注解信 ...
随机推荐
- [kata] Playing with digits
package kata_011; /** * Some numbers have funny properties. For example: * * 89 --> 8¹ + 9² = 89 ...
- Mininet实验 测量路径损耗率
参照:基于Mininet测量路径的损耗率 在SDN环境中,可以利用控制器来测量特定路径的损耗率,在本实验中,基于Mininet脚本,设置特定的交换机间的路径损耗速率,然后编写POX脚本,实现对路径的损 ...
- eclipse中下载maven插件解决办法
https://blog.csdn.net/qq_30546099/article/details/71195446 解决Eclipse Maven插件的最佳方案 https://www.cnblog ...
- python 查找
class py_solution: def twoSum(self, nums, target): lookup = {} for i, num in enumerate(nums): if tar ...
- css3 属性——calc()
其实在之前学习CSS3的时候,我并没有注意到有calc()这个属性,后来在看一个大牛的代码的时候看到了这个,然后就引发了后来的一系列的查找.学习,以及这篇博客的诞生.好了,废话不多说了,来干正事. 一 ...
- Jenkins+Sonar集成对代码进行持续检测
介绍 SonarQube(曾用名Sonar(声纳)[1])是一个开源的代码质量管理系统. 特征 支持超过25种编程语言[2]:Java.C/C++.C#.PHP.Flex.Groovy.JavaScr ...
- 阅读和设计源码利器UML
https://www.w3cschool.cn/uml_tutorial/ 就不做特殊说明了啊: 一 UML 1 简介 类注释: 下面的图表示的 UML 类,该图被分为四个部分. 顶端部分被用来命名 ...
- ExtJS 6 如何引入Dashboard模版
最近很多人问我在ext js 6+的版本中怎么引入官方的dashboard模版,正好我好久没写博客了,这里我写一篇博客来说明一下. 在这里以ext js 6.2.1版本为例(注:需要安装Sencha ...
- 理解 Socket
原文链接 题外话 前几天和朋友聊天,朋友问我怎么最近不写博客了,一个是因为最近在忙着公司使用的一些控件的开发,浏览器兼容性搞死人 但主要是因为这段时间一直在看html5的东西,看到web socket ...
- I.MX6 CAAM
/********************************************************************************* * I.MX6 CAAM * 说明 ...