springWebsocket
来源:互联网 发布:java开发的简单小游戏 编辑:程序博客网 时间:2024/06/14 00:00
教程
一:jar包
maven配置
<!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-websocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
注意:spring-websocket的包版本要与spring的包版本保持一致,不然可能在项目启动的时候回报错;
一:.WebSocketConfig.java (websocket核心配置文件,可以配置websocket的映射路径,监听等功能)
内容代码如下
:
@Configuration
@ComponentScan(basePackages= {"com.config.websocket"})
@EnableWebSocket
public class WebSocketConfig extendsWebMvcConfigurerAdapterimplements WebSocketConfigurer{
@Resource
MyWebSocketHandlerhandler;
public voidregisterWebSocketHandlers(WebSocketHandlerRegistry registry){
registry.addHandler(handler,"/ws.json").addInterceptors(new HandShake()).setAllowedOrigins("*");
registry.addHandler(handler,"/ws/sockjs").addInterceptors(new HandShake()).withSockJS();
}
}
@Configuration 指明该类为Spring 配置类
@EnableWebSocket 声明该类支持WebSocket
红色方框表示 handler(消息处理对象)位置;
红色横线表示将ws:hostPath/ws.json的请求映射到handle消息处理类中;注意:配置路径时候注意项目springMvc的捕获请求的路径,不然在项目中会找不到请求,我的项目中springmvc后缀为json所以是/ws.json;
荧光绿波浪线表示注册自定义的拦截器的位置;拦截器是SpringWebsocket提供的功能,并非websocket所必须的配置,可自行根据业务进行选择是否配置;
黄色横线 setAllowedOrigins方法用来设置来自那些域名的请求可访问,默认为localhost ,不设置的话socket链接的时候会被拒绝:提示 Unexpected response code: 403;(深坑)
二:MyWebSocketHandler.java(消息处理类,实现WebSocketHandler接口,里面有socket声明周期的所有方法)
对应链接,建立,前台发送消息,链接关闭等方法 都是相应api 没有什么很奇怪的点;后台向浏览器推送消息,就使用WebSocketSession的sendMessage方法
三:自定义的拦截器;
public class HandShake implementsHandshakeInterceptor{
public booleanbeforeHandshake(ServerHttpRequest request,ServerHttpResponse response,WebSocketHandler wsHandler,Map<String,Object> attributes)throwsException {
// System.out.println("Websocket:用户[ID:" + ((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("uid") + "]已经建立连接");
// if (request instanceof ServletServerHttpRequest) {
// ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
// HttpSession session = servletRequest.getServletRequest().getSession(false);
// // 标记用户
// Long uid = (Long) session.getAttribute("uid");
// if(uid!=null){
// attributes.put("uid", uid);
// }else{
// return false;
// }
// }
System.out.println("拦截器拦截到ws请求");
return true;
}
public voidafterHandshake(ServerHttpRequest request,ServerHttpResponse response,WebSocketHandler wsHandler,Exception exception){
}
}
实现HandshakeInterceptor接口,实现beforeHandshake方法,true表示放行请求,可以进行权限或者公共信息处理;
前台调用的代码
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + path + "/ws?uid="+uid);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://" + path + "/ws"+uid);
} else {
websocket = new SockJS("http://" + path + "/ws/sockjs"+uid);
}
websocket.onopen = function(event) {
console.log("WebSocket:已连接");
console.log(event);
};
websocket.onmessage = function(event) {
var data=JSON.parse(event.data);
console.log("WebSocket:收到一条消息",data);
};
websocket.onerror = function(event) {
console.log("WebSocket:发生错误 ");
console.log(event);
};
websocket.onclose = function(event) {
console.log("WebSocket:已关闭");
console.log(event);
}
阅读全文
0 0
- springWebsocket
- springwebsocket部署的一次坑
- SpringWebsocket +Stomp+SockJS实现消息订阅和推送
- 如何搭建SpringWebSocket以及搭建中一些常到的问题
- 关于axios
- 计算机博弈-最大最小搜索,Alpha-Beta搜索
- 反向传播
- React Native导航器之react-navigation使用
- 数塔
- springWebsocket
- 链表的归并排序
- 用异或运算实现两个数字的交换(装x)
- 感知机/Pytorch—笔记
- JS中的系统对象
- 洛谷 P3817 小A的糖果
- django {{ MEDIA_URL }}值为空
- Python笔记
- Leetcode之Container With Most Water 问题