springmvc集成websocket
springmvc集成websocket
环境:spring+springmvc+tomcat8
注意:本测试项目 运行环境不能低于tomcat8
1.websocket配置
package club.jiajiajia.connom.service.impl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
/**
* webSocket配置
* @author LENOVO
*/
@Configuration
@EnableWebSocket
@EnableWebMvc
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(myHandler(),"/socket.do").addInterceptors(new HandshakeInterceptor());
webSocketHandlerRegistry.addHandler(myHandler(),"/socket/info").addInterceptors(new HandshakeInterceptor()).withSockJS();
}
@Bean
public WebSocketHandler myHandler(){
return new WebSocketHandler();
}
}
2.会话拦截器
package club.jiajiajia.connom.service.impl;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import java.util.Map;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 会话拦截器
* @author LENOVO
*/
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
HttpSession session = servletRequest.getSession();
String id=(String) session.getAttribute("socketId");
if(id!=null&&servletRequest.getParameter("type").equals(id)) {
attributes.put("socketId",id);
return super.beforeHandshake(request, response, wsHandler, attributes);
}else {
return false;
}
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
3.websocket消息处理器
package club.jiajiajia.connom.service.impl;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
* websocket处理器
* @author LENOVO
*/
public class WebSocketHandler extends TextWebSocketHandler {
public static Map<String,WebSocketSession> map=new HashMap<String,WebSocketSession>();
private String id;
//连接建立后处理
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
String id=(String) session.getAttributes().get("socketId");
this.id=id;
System.out.println(id+":建立链接");
if(!map.containsKey(id)) {
map.put(id, session);
}else {
session.close();
}
super.afterConnectionEstablished(session);
}
//抛出异常时处理
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if(session.isOpen()){
session.close();
if(map.containsKey(this.id)) {
map.remove(this.id);
}
}
}
//连接关闭后处理
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
try {
if(map.containsKey(this.id)) {
map.remove(this.id);
}
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//接收文本消息,并发送出去
@Override
protected void handleTextMessage(WebSocketSession session,TextMessage message) throws Exception {
super.handleTextMessage(session, message);
}
public static boolean sendMessage(String id,String message) {
if(map.containsKey(id)) {
WebSocketSession session=map.get(id);
TextMessage m=new TextMessage(message);
try {
session.sendMessage(m);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}else {
return false;
}
}
}
4.applicationContext.xml配置
<!-- 配置好处理器 -->
<bean id="websocketHandler" class="club.jiajiajia.connom.service.impl.WebSocketHandler"/>
<!-- 配置拦截器 -->
<websocket:handlers>
<websocket:mapping path="/socket.do" handler="websocketHandler"/><!-- 连接的URL -->
<websocket:handshake-interceptors>
<bean class="club.jiajiajia.connom.service.impl.HandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>
5.测试controller
package club.jiajiajia.connom.controller;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import club.jiajiajia.connom.service.impl.WebSocketHandler;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/test")
public String test(HttpSession session,String id) {
session.setAttribute("socketId",id);
return "index2";
}
@RequestMapping("/send")
@ResponseBody
public String test(HttpSession session,String id,String message) {
try {
WebSocketHandler.sendMessage(id, message);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "send error";
}
return "send success";
}
}
6.简单jsp测试页面
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试</title>
</head>
<body>
<div>
测试 websocket
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var ws;
window.onload=connect;
function connect(){
if ('WebSocket' in window) {
ws = new WebSocket("ws://"+window.location.host+"/websocket/socket.do?type=123");
} else {
ws = new SockJS("http://"+window.location.host+"/websocket/socket/info?type=123");
}
ws.onopen = function (evnt) {
console.log("websocket连接成功");
};
ws.onmessage = function (evnt) {
console.log("websocket接收到一条新消息:");
console.log(evnt);
};
ws.onerror = function (evnt) {
};
ws.onclose = function (evnt) {
}
}
</script>
</body>
</html>
添加的依赖如下:
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
spring配置文件头文件
xmlns:websocket="http://www.springframework.org/schema/websocket"
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd
7.看看效果
地址:http://localhost:8080/websocket/test/test?id=123
然后向上一个链接发送消息:http://localhost:8080/websocket/test/send?id=123&message=哈哈哈,该回家吃饭了
回到上一个页面看看结果
发送成功
本项目只是做一个简单的测试
如果有兴趣的话可以尝试设计更复杂的demo
评论区
请写下您的评论...
猜你喜欢
框架
8223
上次我们说了spring集成websocket,实现用websocket通讯集成配置连接:http://www.jiajiajia.club/weblog/blog/artical/128下面来模拟
框架
1284
/groupIdartifactIdkaptcha/artifactIdversion${kaptcha.version}/version/dependency生成验证码的配置类importcom.google
java序列化储存
2781
序列化和反序列化请参考:http://www.jiajiajia.club/blog/artical/yjw520/161源码下载地址:http://photo.jiajiajia.club/file/blob.rarcontroller层代码:importorg.springframework.beans.factory.annotation.Autowired;importorg.spring
nginx,前端,java基础
1998
基于javanio+netty+websocket+protobuf+javascript等技术实现前后端高性能实时数据传输的demo模型。 github地址:https
框架
2917
1.配置springboot支持websocketpackagecom.example.demo.websocket;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.so
official
1450
基于javanio+netty+websocket+protobuf+javascript等技术实现前后端高性能实时数据传输的demo模型。 github地址:https
official
1157
Websocket协议和http协议的关系websocket是基于TCP的一个应用协议,与HTTP协议的关联之处在于websocket的握手数据被HTTP服务器当作HTTP包来处理,主要通过
spring/springmvc
1701
springmvc+mybatis整合shiro权限1.需要的jar包propertiesshiro.version1.3.2/shiro.version/propertiesdependency
最新发表
归档
2018-11
12
2018-12
33
2019-01
28
2019-02
28
2019-03
32
2019-04
27
2019-05
33
2019-06
6
2019-07
12
2019-08
12
2019-09
21
2019-10
8
2019-11
15
2019-12
25
2020-01
9
2020-02
5
2020-03
16
2020-04
4
2020-06
1
2020-07
7
2020-08
13
2020-09
9
2020-10
5
2020-12
3
2021-01
1
2021-02
5
2021-03
7
2021-04
4
2021-05
4
2021-06
1
2021-07
7
2021-08
2
2021-09
8
2021-10
9
2021-11
16
2021-12
14
2022-01
7
2022-05
1
2022-08
3
2022-09
2
2022-10
2
2022-12
5
2023-01
3
2023-02
1
2023-03
4
2023-04
2
2023-06
3
2023-07
4
2023-08
1
2023-10
1
2024-02
1
2024-03
1
2024-04
1
2024-08
1
标签
算法基础
linux
前端
c++
数据结构
框架
数据库
计算机基础
储备知识
java基础
ASM
其他
深入理解java虚拟机
nginx
git
消息中间件
搜索
maven
redis
docker
dubbo
vue
导入导出
软件使用
idea插件
协议
无聊的知识
jenkins
springboot
mqtt协议
keepalived
minio
mysql
ensp
网络基础
xxl-job
rabbitmq
haproxy
srs
音视频
webrtc
javascript
加密算法
目录
没有一个冬天不可逾越,没有一个春天不会来临。最慢的步伐不是跬步,而是徘徊,最快的脚步不是冲刺,而是坚持。