WebSocket使用总结

WebSocket是一种在服务器和客户端之间实现双向通信的协议,允许服务器主动推送信息。在Java SpringBoot中,可以通过ServerEndpointExporter配置WebSocket,结合ServerEndpointConfig.Configurator处理HTTP会话,并实现URL参数传递。
摘要由CSDN通过智能技术生成

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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星仔说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值