Springboot2.0集成webSocket以及常见问题

1、WebSocket和http的区别?

1、http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息。

http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息。即每一个request对应一个response。长链接是在一定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。
2、WebSocket
WebSocket他是为了解决客户端发起多个http请求到服务器资源浏览器必须要经过长时间的轮训问题而生的,他实现了多路复用,他是全双工通信。在webSocket协议下客服端和浏览器可以同时发送信息。

2、实例

(1)添加maven依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
   </dependency>

(2)核心代码

@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {
    
    

    @PostConstruct
    public void init() {
    
    
        System.out.println("websocket 加载");
    }
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
    
    
        SessionSet.add(session);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("有连接加入,当前连接数为:{}", cnt);
        SendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
    
    
        SessionSet.remove(session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭,当前连接数为:{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     *            客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    
    
        log.info("来自客户端的消息:{}",message);
        SendMessage(session, "收到消息,消息内容:"+message);

    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
    
    
        log.error("发生错误:{},Session ID: {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息,实践表明,每次浏览器刷新,session会发生变化。
     * @param session
     * @param message
     */
    public static void SendMessage(Session session, String message) {
    
    
        try {
    
    
            session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
        } catch (IOException e) {
    
    
            log.error("发送消息出错:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public static void BroadCastInfo(String message) throws IOException {
    
    
        for (Session session : SessionSet) {
    
    
            if(session.isOpen()){
    
    
                SendMessage(session, message);
            }
        }
    }

    /**
     * 指定Session发送消息
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void SendMessage(String message,String sessionId) throws IOException {
    
    
        Session session = null;
        for (Session s : SessionSet) {
    
    
            if(s.getId().equals(sessionId)){
    
    
                session = s;
                break;
            }
        }
        if(session!=null){
    
    
            SendMessage(session, message);
        }
        else{
    
    
            log.warn("没有找到你指定ID的会话:{}",sessionId);
        }
    }

}

3、常见问题(出现404错误)

原因:这是因为websocket创建的bean是由自己来管理的,需要将其创建的bean交给spring管理

解决方案

@Configuration
public class WebSocketConfig {
    
    
    /**
     * ServerEndpointExporter 作用
     *
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     *
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
    
    
        return new ServerEndpointExporter();
    }
    @Bean
    public MySpringConfigurator mySpringConfigurator() {
    
    
        return new MySpringConfigurator();
    }
}


/**
 * 以websocketConfig.java注册的bean是由自己管理的,需要使用配置托管给spring管理
 *
  */

public class MySpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    
    

    private static volatile BeanFactory context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        MySpringConfigurator.context = applicationContext;
    }

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
    
    
        return context.getBean(clazz);
    }
}


spring就可以获取到websocket所创建的bean了

猜你喜欢

转载自blog.csdn.net/CharlesYooSky/article/details/112857655