WebSocket
特点
- 全双工通信,客户端和服务器可以双向平等通信;
- 建立在TCP协议之上,服务器端的实现比较容易;
- 数据格式比较轻量,性能开销小,通信高效;
- 可以发送文本,也可以发送二进制数据;
- 通信具有更强的实时性;
- 协议标识符是ws,服务器地址就是:
ws://www.abc.com/some/path
- http协议:
http://
Websocket开发相关注解及API方法
-
@ServerEndpoint("/websocket/{uid}")
申明这是一个websocket服务 -
@OnOpen
该方法将在建立连接后执行,会传入session对象,就是客户端与服务端建立的长连接通道,通过@PathParam获取url中声明的参数
用法:public void onOpen(Session session, @PathParam("uid") String uid) throws IOException{}
-
@OnClose
该方法是在连接关闭后执行;
用法:public void onClose() {}
-
@OnMessage
该方法用于接收客户端发送的消息;
message: 发来的消息数据
session:会话对象(也是长连接通道)用法:
public void onMessage(String message, Session session) throws IOException {}
发送消息到客户端,通过session进行消息发送;
public void onMessage(String message, Session session) throws IOException {
session.getBasicRemote().sendText("hello,websocket.");
}
第三方商业方案goeasy
GoEasy实时Web推送,支持后台推送和前台推送两种:
- 后台推送可以选择Java SDK、Restful API支持所有开发语言;
- 前台推送:JS推送,由于它支持websocket 和polling两种连接方式所以兼顾大多数主流浏览器,低版本的IE浏览器也是支持的;
- 地址:http://goeasy.io/
Websocket各浏览器的支持情况:
https://caniuse.com/#search=websocket
springboot继承websocket
配置类模板
@EnableWebSocket //启用WebSocket支持
@Configuration //表示配置类
public class WebSocketConfig {
/**
* 配置ServerEndpointExporter的bean
* 该Bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
服务器类配置
//@ServerEndpoint注解中指定WebSocket协议的地址;
//@OnOpen、@OnMessage、@OnClose、@OnError注解与WebSocket中监听事件对应
@Component
@ServerEndpoint("/websocket/{username}")
public class xxx {
}