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("連接關閉"); }}
|
新聞熱點
疑難解答