Spring和Websocket相结合实现消息的推送

网友投稿 202 2023-07-22


Spring和Websocket相结合实现消息的推送

本文主要有三个步骤

1、用户登录后建立websocket连接,默认选择websocket连接,如果浏览器不支持,则使用sockjs进行模拟连接

2、建立连接后,服务端返回该用户的未读消息

3、服务端进行相关操作后,推送给某一个用户或者所有用户新消息 相关环境 Spring4.0.6(要选择4.0+),tomcat7.0.55

Websocet服务端实现

WebSocketConfig.java

@Configuration

@EnableWebMvc

@EnableWebSocket

public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

@Override

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor());

registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())

.withSockJS();

}

@Bean

public WebSocketHandler systemWebSocketHandler(){

return new SystemWebSocketHandler();

}

}

不要忘记在springmvc的配置文件中配置对此类的自动扫描

@Configuration

@EnableWebMvc

@EnableWebSocket

这三个大致意思是使这个类支持以@Bean的方式加载bean,并且支持springmvc和websocket,不是很准确大致这样,试了一下@EnableWebMvc不加也没什么影响,@Configuration本来就支持springmvc的自动扫描

registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())

用来注册websocket server实现类,第二个参数是访问websocket的地址

registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())

.withSockJS();

}

这个是使用Sockjs的注册方法

首先SystemWebSocketHandler.java

public class SystemWebSocketHandler implements WebSocketHandler {

private static final Logger logger;

private static final ArrayList users;

static {

users = new ArrayList<>();

logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);

}

@Autowired

private WebSocketService webSocketService;

@Override

public void afterConnectionEstablished(WebSocketSession session) throws Exception {

logger.debug("connect to the websocket success......");

users.add(session);

String userName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);

if(userName!= null){

//查询未读消息

int count = webSocketService.getUnReadNews((String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME));

session.sendMessage(new TextMessage(count + ""));

}

}

@Override

public void handleMessage(WebSocketSession session, WebSocketMessage> message) throws Exception {

//sendMessageToUsers();

}

@Override

public void handleTransportError(WebSocketSession session, Throwable exceLTvkabiption) throws Exception {

if(session.isOpen()){

session.close();

}

logger.debug("websocket connection closed......");

users.remove(session);

}

@Override

public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

logger.debug("websocket connection closed......");

users.remove(session);

}

@Override

public boolean supporhttp://tsPartialMessages() {

return false;

}

/**

* 给所有在线用户发送消息

*

* @param message

*/

public void sendMessageToUsers(TextMessage message) {

for (WebSocketSession user : users) {

try {

if (user.isOpen()) {

user.sendMessage(message);

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 给某个用户发送消息

*

* @param userName

* @param message

*/

public void sendMessageToUser(String userName, TextMessage message) {

for (WebSocketSession user : users) {

if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {

try {

if (user.isOpen()) {

user.sendMessage(message);

}

} catch (IOException e) {

e.printStackTrace();

}

break;

}

}

}

}

相关内容大家一看就能明白,就不多解释了

然后WebSocketHandshakeInterceptor.java

public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

private static Logger logger = LoggerFactory.getLogger(HandshakeInterceptor.class);

@Override

public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map

> attributes) throws Exception {

if (request instanceof ServletServerHttpRequest) {

ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;

HttpSession session = servletRequest.getServletRequest().getSession(false);

if (session != null) {

//使用userName区分WebSocketHandler,以便定向发送消息

String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

attributes.put(Constants.WEBSOCKET_USERNAME,userName);

}

}

return true;

}

@Override

public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

}

}

这个的主要作用是取得当前请求中的用户名,并且保存到当前的WebSocketHandler中,以便确定WebSocketHandler所对应的用户,具体可参考HttpSessionHandshakeInterceptor

用户登录建立websocket连接

index.jsp

使用sockjs时要注意

1、这两个的写法

websocket = new SockJS(http://localhost:8080/Origami/sockjs/webSocketServer);

2、web.xml中

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

http://

version

web-app_3_1.xsd

这两个的版本都要是3.0+

然后在这个servlet中加入

true

appServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath*:servlet-context.xml

1

true

然后所有的filter中也加入

true

3、添加相关依赖

com.fasterxml.jackson.core

jackson-annotations

2.3.0

com.fasterxml.jackson.core

jackson-core

2.3.1

com.fasterxml.jackson.core

jackson-databind

2.3.3

好了,现在websocket可以正常建立起来了

返回用户未读的消息

当连接建立后,会进入SystemWebSocketHandler的afterConnectionEstablished方法,代码看上边,取出WebSocketHandshakeInterceptor中保存的用户名

查询信息后使用session.sendMessage(new TextMessage(count + ""));返回给用户,从哪来回哪去

服务端推送消息给用户

@Controller

public class AdminController {

static Logger logger = LoggerFactory.getLogger(AdminController.class);

@Autowired(required = false)

private AdminService adminService;

@Bean

public SystemWebSocketHandler systemWebSocketHandler() {

return new SystemWebSocketHandler();

}

@RequestMapping("/auditing")

@ResponseBody

public String auditing(HttpServletRequest request){

//无关代码都省略了

int unReadNewsCount = adminService.getUnReadNews(username);

systemWebSocketHandler().sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));

return result;

}

}

在这里可以使用sendMessageToUser给某个用户推送信息,也可以使用sendMessageToUsers给所有用户推送信息

> attributes) throws Exception {

if (request instanceof ServletServerHttpRequest) {

ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;

HttpSession session = servletRequest.getServletRequest().getSession(false);

if (session != null) {

//使用userName区分WebSocketHandler,以便定向发送消息

String userName = (String) session.getAttribute(Constants.SESSION_USERNAME);

attributes.put(Constants.WEBSOCKET_USERNAME,userName);

}

}

return true;

}

@Override

public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

}

}

这个的主要作用是取得当前请求中的用户名,并且保存到当前的WebSocketHandler中,以便确定WebSocketHandler所对应的用户,具体可参考HttpSessionHandshakeInterceptor

用户登录建立websocket连接

index.jsp

使用sockjs时要注意

1、这两个的写法

websocket = new SockJS(http://localhost:8080/Origami/sockjs/webSocketServer);

2、web.xml中

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

http://

version

web-app_3_1.xsd

这两个的版本都要是3.0+

然后在这个servlet中加入

true

appServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath*:servlet-context.xml

1

true

然后所有的filter中也加入

true

3、添加相关依赖

com.fasterxml.jackson.core

jackson-annotations

2.3.0

com.fasterxml.jackson.core

jackson-core

2.3.1

com.fasterxml.jackson.core

jackson-databind

2.3.3

好了,现在websocket可以正常建立起来了

返回用户未读的消息

当连接建立后,会进入SystemWebSocketHandler的afterConnectionEstablished方法,代码看上边,取出WebSocketHandshakeInterceptor中保存的用户名

查询信息后使用session.sendMessage(new TextMessage(count + ""));返回给用户,从哪来回哪去

服务端推送消息给用户

@Controller

public class AdminController {

static Logger logger = LoggerFactory.getLogger(AdminController.class);

@Autowired(required = false)

private AdminService adminService;

@Bean

public SystemWebSocketHandler systemWebSocketHandler() {

return new SystemWebSocketHandler();

}

@RequestMapping("/auditing")

@ResponseBody

public String auditing(HttpServletRequest request){

//无关代码都省略了

int unReadNewsCount = adminService.getUnReadNews(username);

systemWebSocketHandler().sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));

return result;

}

}

在这里可以使用sendMessageToUser给某个用户推送信息,也可以使用sendMessageToUsers给所有用户推送信息

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">

http://

version

web-app_3_1.xsd

这两个的版本都要是3.0+

然后在这个servlet中加入

true

appServlet

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath*:servlet-context.xml

1

true

然后所有的filter中也加入

true

3、添加相关依赖

com.fasterxml.jackson.core

jackson-annotations

2.3.0

com.fasterxml.jackson.core

jackson-core

2.3.1

com.fasterxml.jackson.core

jackson-databind

2.3.3

好了,现在websocket可以正常建立起来了

返回用户未读的消息

当连接建立后,会进入SystemWebSocketHandler的afterConnectionEstablished方法,代码看上边,取出WebSocketHandshakeInterceptor中保存的用户名

查询信息后使用session.sendMessage(new TextMessage(count + ""));返回给用户,从哪来回哪去

服务端推送消息给用户

@Controller

public class AdminController {

static Logger logger = LoggerFactory.getLogger(AdminController.class);

@Autowired(required = false)

private AdminService adminService;

@Bean

public SystemWebSocketHandler systemWebSocketHandler() {

return new SystemWebSocketHandler();

}

@RequestMapping("/auditing")

@ResponseBody

public String auditing(HttpServletRequest request){

//无关代码都省略了

int unReadNewsCount = adminService.getUnReadNews(username);

systemWebSocketHandler().sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));

return result;

}

}

在这里可以使用sendMessageToUser给某个用户推送信息,也可以使用sendMessageToUsers给所有用户推送信息


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java实现简单的搜索引擎
下一篇:全方位讲解Java的面向对象编程思想
相关文章

 发表评论

暂时没有评论,来抢沙发吧~