首页 > 学院 > 开发设计 > 正文

spring websocket的应用

2019-11-10 21:08:42
字体:
来源:转载
供稿:网友

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("连接关闭");    }}


上一篇:JVM-GC设计思路分析

下一篇:对象数组

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表