sPRing4之后的一个新特性就是整合了websocket
首先在pom.xml加入
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.2.8.RELEASE</version> </dependency>
然后利用@Configuration配置websocket
@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // TODO Auto-generated method stub System.out.println("启动websocket"); registry.addHandler(new TestHandler(), "/test").addInterceptors(new HandshakeInterceptor()); }}
其中“/test”就是url,后面可以增加一个拦截器。
public class TestHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketsession session, TextMessage message) throws Exception { //具体的业务逻辑写在这 } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { // TODO Auto-generated method stub System.out.println("websocket启动"); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { // TODO Auto-generated method stub System.out.println(exception); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { // TODO Auto-generated method stub System.out.println("连接关闭"); }}
新闻热点
疑难解答