概要

  • 2018年第一天上班
  • WebSocket 简介
  • spring-boot-websocket的使用

前言: 2018年上班第一天,没什么事,就将前些天写的一个关于智能面试机器人项目中使用到的websoket总结如下:

WebSocket 简介

WebSocket是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯,它建立在TCP之上,同HTTP一样通过TCP来传输数据,但是它和HTTP最大不同是:

  • WebSocket 是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/Client Agent都能主动的向对方发送或接收数据,就像Socket一样;
  • WebSocket 需要类似TCP的客户端和服务器端通过握手连接,连接成功后才能相互通信。

spring-boot-websocket的使用

1.maven依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

3.配置文件

  1. @Component
  2. public class MyEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
  3. private static BeanFactory context;
  4. @Override
  5. public <T> T getEndpointInstance(Class<T> clazz) {
  6. return context.getBean(clazz);
  7. }
  8. @Override
  9. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  10. MyEndpointConfigure.context = applicationContext;
  11. }
  12. }
  1. @Configuration
  2. public class WebSocketConfig {
  3. @Bean
  4. public ServerEndpointExporter serverEndpointExporter() {
  5. return new ServerEndpointExporter();
  6. }
  7. }

3.核心websocket

特别注意: 不能使用默认的ServerEndpointConfig.Configurator.class,不然会导致服务无法注入

  1. @ServerEndpoint(value = "/websocket", configurator = MyEndpointConfigure.class)
  2. @Component
  3. public class WebSocket {
  4. /**
  5. * 成功建立连接调用的方法.
  6. */
  7. @OnOpen
  8. public void onOpen(Session session) {
  9. }
  10. /**
  11. * 连接关闭调用的方法.
  12. */
  13. @OnClose
  14. public void onClose(Session session) {
  15. }
  16. /**
  17. * 收到客户端消息后调用的方法.
  18. */
  19. @OnMessage
  20. public void onMessage(String message, Session session) {
  21. }
  22. /**
  23. * 发生错误时调用.
  24. */
  25. @OnError
  26. public void onError(Session session, Throwable error) {
  27. }
  28. }