SpringBoot整合WebSocket

2018-09-27 22:38:11

SpringBoot 整合WebSocket

依赖导入

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

@Configuration 配置

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  4. @Configuration
  5. public class WebSocketConfiguration {
  6. @Bean
  7. public ServerEndpointExporter serverEndpointExporter (){
  8. return new ServerEndpointExporter();
  9. }
  10. }

端点创建

  1. import java.io.IOException;
  2. import javax.websocket.CloseReason;
  3. import javax.websocket.EndpointConfig;
  4. import javax.websocket.OnClose;
  5. import javax.websocket.OnError;
  6. import javax.websocket.OnMessage;
  7. import javax.websocket.OnOpen;
  8. import javax.websocket.Session;
  9. import javax.websocket.server.ServerEndpoint;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.stereotype.Component;
  13. @Component
  14. @ServerEndpoint(value = "/channel/test")
  15. public class TestChannel {
  16. private static final Logger LOGGER = LoggerFactory.getLogger(TestChannel.class);
  17. private Session session;
  18. @OnMessage(maxMessageSize = 10)
  19. public void onMessage(byte[] message){
  20. //skip
  21. }
  22. @OnOpen
  23. public void onOpen(Session session, EndpointConfig endpointConfig){
  24. LOGGER.info("新的连接,id={}",session.getId());
  25. session.setMaxIdleTimeout(0);
  26. this.session = session;
  27. }
  28. @OnClose
  29. public void onClose(CloseReason closeReason){
  30. LOGGER.info("连接断开,id={} reason={}",this.session.getId(),closeReason);
  31. }
  32. @OnError
  33. public void onError(Throwable throwable) throws IOException {
  34. LOGGER.info("连接异常,id={},throwable={}",this.session.getId(),throwable);
  35. this.session.close();
  36. throwable.printStackTrace();
  37. }
  38. }

注意

Endpoint 端点实例是由Servlet容器创建的(未由spring管理),所以在里面使用spring的注入@Autowired会无效


0
0
0

添加评论

正在回复:
取消
1
0
0
0