SpringBoot实现WebSocket服务
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
@Component @ServerEndpoint("/websocket") @EnableWebSocket @SpringBootApplication public class DemoApplication { private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public ServerEndpointExporter serverEndpoint() { return new ServerEndpointExporter(); } @OnOpen public void onOpen(Session session) { logger.info("websocket onOpen, session_id: " + session.getId()); } @OnClose public void onClose(Session session) { logger.info("websocket onClose, session_id: " + session.getId()); } @OnMessage public void onMessage(String message, Session session) { logger.info("websocket onMessage, session_id: " + session.getId() + ", message: " + message); } @OnError public void error(Session session, Throwable e) { logger.info("websocket error, session_id: " + session.getId() + ", e: " + e.getMessage()); } }