一、背景
二、具体分析
1、交互的过程则要求前端和后台都能主动发起请求,这有区别于常见的http
2、websocket的定义:
一种在单个TCP连接上进行全双工通信(双向通信)的协议
3、概述:
三、实现
1、端点信息设置
1 @Configuration 2 @EnableWebSocketMessageBroker //启动websocket端点 3 public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { 4 5 /** 6 * 握手拦截器 7 */ 8 @Autowired 9 private WsHandShakeInterceptor wsHandShakeInterceptor; 10 /* (non-Javadoc) 11 * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer#registerStompEndpoints(org.springframework.web.socket.config.annotation.StompEndpointRegistry) 12 */ 13 @Override 14 public void registerStompEndpoints(StompEndpointRegistry registry) { 15 registry 16 .addEndpoint("/ws")//设置端点名称 17 .setHandshakeHandler(new MyPrincipalHandshakeHandler()) //设置义用户和websocket的绑定策略,如新用户使用session以及用户的校验,是否登录,返回Principal实现类 18 // .setAllowedOrigins("*") // 添加允许跨域访问 19 // .setAllowedOrigins("http://mydomain.com"); 20 .addInterceptors(wsHandShakeInterceptor) // 添加自定义拦截,如握手前设置上下文信息 21 .withSockJS(); //withSockJS允许客户端利用sockjs进行浏览器兼容性处理 22 } 23 24 /* (non-Javadoc) 25 * @see org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer#configureMessageBroker(org.springframework.messaging.simp.config.MessageBrokerRegistry) 26 */ 27 @Override 28 public void configureMessageBroker(MessageBrokerRegistry registry) { 29 registry.setApplicationDestinationPrefixes("/app");//设置客户端订阅消息的基础逻辑,默认也是这个,前端url中提现 30 registry.enableSimpleBroker("/topic"); // 设置服务端广播消息的基础路径,默认也是这个,后端提现 31 32 33 // Use this for enabling a Full featured broker like RabbitMQ 34 35 /* 36 registry.enableStompBrokerRelay("/topic") 37 .setRelayHost("localhost") 38 .setRelayPort(61613) 39 .setClientLogin("guest") 40 .setClientPasscode("guest"); 41 */ 42 } 43 }
2、contoller设置
1 @Controller 2 public class WebSocketAction { 3 4 private Logger logger = LoggerFactory.getLogger(this.getClass()); 5 6 @MessageMapping("/sendTest") 7 @SendTo("/topic/subscribeTest") //结果推送客户端,订阅了/topic/subscribeTest的客户端 8 public ServerMessage sendDemo(ClientMessage message) { 9 logger.info("接收到了信息" + message.getName()); 10 return new ServerMessage("你发送的消息为:" + message.getName()); 11 } 12 13 @SubscribeMapping("/subscribeTest") 14 public ServerMessage sub() { 15 logger.info("XXX用户订阅了我。。。"); 16 return new ServerMessage("感谢你订阅了我。。。"); 17 } 18 19 }
ps:
1、@MessageMapping(“/sendTest”) 接收客户端发送的信息,发送的url是/app/sendTest(经由消息代理)
2、@SubscribeMapping(“/subscribeTest”) ,和MessageMapping功能类似,不经由消息代理
3、@SendTo(“/topic/subscribeTest”) 返回目的地的地址,经由消息代理,所有订阅改路径的客户端都能收到
4、@SendToUser(value = "/topic/greetings",broadcast = false) 与sendTo功能类似,但只有订阅了改路径的消息发起者能收到信息
原文:https://www.cnblogs.com/ws563573095/p/10402469.html