WebSocket使用总结
是什么
WebSocket 协议在2008年诞生,2011年成为国际标准。所有浏览器都已经支持了。
它的最大特点就是,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息,是真正的双向平等对话,属于服务器推送技术的一种。
其他特点包括:
(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws
(如果加密,则为wss
),服务器网址就是 URL。
怎么用(java+springboot)
配置
@Configuration
public class WebSocketConfig {
public WebSocketConfig() {
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
ServerEndpointExporter的作用是将@ServerEndpoint 注解的类 注入到容器中,源码如下getBeanNamesForAnnotation(ServerEndpoint.class)
protected void registerEndpoints() {
Set<Class<?>> endpointClasses = new LinkedHashSet<>();
if (this.annotatedEndpointClasses != null) {
endpointClasses.addAll(this.annotatedEndpointClasses);
}
ApplicationContext context = getApplicationContext();
if (context != null) {
String[] endpointBeanNames = context.getBeanNamesForAnnotation(ServerEndpoint.class);
for (String beanName : endpointBeanNames) {
endpointClasses.add(context.getType(beanName));
}
}
使用示例
通过配置ServerEndpointConfig.Configurator将httpsession 加入到websocket中
public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator{
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
super.modifyHandshake(sec, request, response);
}
}
@ServerEndpoint(value="/ui/eventMonitorServer/{userId}",configurator = HttpSessionConfigurator.class)
@Service("eventMonitorServer")
public class EventMonitorServer {
//静态变量,用来记录当前在线连接数
private static AtomicLong onlineCount = new AtomicLong();
//记录每个用户下多个终端的连接
private static Map<String, Set<EventMonitorServer>> userSocket = new HashMap<>();
//需要session来对用户发送数据, 获取连接特征userId
private Session session;