java怎么拦截某个对象
265
2022-12-03
Spring Boot 整合单机websocket的步骤 附github源码
wWEvnkOYFAebsocket 概念
websocket 是一个通信协议,通过单个 TCP 连接提供全双工通信。websocket 连接成功后,服务端和客户可以进行双向通信。不同于 http 通信协议需要每次由WEvnkOYFA客户端发起,服务响应到客户端。
websocket 相对轮询也能节约带宽,并且能实时的进行通信。
整合步骤
1. 添加 maven 依赖
添加web、websocket和freemarker依赖。
2. 使用 ServerEndpointExporter 创建 bean
这个 bean 会自动注册声明 @ServerEndpoint 注解声明的 websocket endpoint,使用springboot自带tomcat启动需要该配置,使用独立 tomcat 则不需要该配置。
@Configuration
public class WebSocketConfig {
//tomcat启动无需该配置
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3. 创建服务端端点 (ServerEndpoint)
@Component
@ServerEndpoint(value = "/message")
@Slf4j
public class WebSocket {
private static Map
private Session session;
@OnOpen
public void onOpen(Session session) throws SocketException {
this.session = session;
webSocketSet.put(this.session.getId(),this);
log.info("【websocket】有新的连接,总数:{}",webSocketSet.size());
}
@OnClose
public void onClose(){
String id = this.session.getId();
ifWEvnkOYFA (id != null){
webSocketSet.remove(id);
log.info("【websocket】连接断开:总数:{}",webSocketSet.size());
}
}
@OnMessage
public void onMessage(String message){
if (!message.equals("ping")){
log.info("【wesocket】收到客户端发送的消息,message={}",message);
sendMessage(message);
}
}
/**
* 发送消息
* @param message
* @return 全部都发送一遍
*/
public void sendMessage(String message){
for (WebSocket webSocket : webSocketSet.values()) {
webSocket.session.getAsyncRemote().sendText(message);
}
log.info("【wesocket】广播消息,message={}", message);
}
}
4. 添加 controller 和 客户端
添加 controller
@GetMapping({"","index.html"})
public ModelAndView index() {
ModelAndView view = new ModelAndView("index");
return view;
}
添加ftl页面
5. 展示效果
附录
github源码
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~