博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring WebSocket实现消息推送
阅读量:6832 次
发布时间:2019-06-26

本文共 8716 字,大约阅读时间需要 29 分钟。

hot3.png

第一步: 添加Spring WebSocket的依赖jar包

(注:这里使用maven方式添加 手动添加的同学请自行下载相应jar包放到lib目录)

org.springframework
spring-websocket
${spring.version}
org.springframework
spring-messaging
${spring.version}

第二步:建立一个类实现WebSocketConfigurer接口

package com.quicksand.push;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;import org.springframework.web.socket.handler.TextWebSocketHandler;@Configuration@EnableWebMvc@EnableWebSocketpublic class SpringWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {        registry.addHandler(webSocketHandler(),"/websocket/socketServer.do").addInterceptors(new SpringWebSocketHandlerInterceptor());        registry.addHandler(webSocketHandler(), "/sockjs/socketServer.do").addInterceptors(new SpringWebSocketHandlerInterceptor()).withSockJS();    }     @Bean    public TextWebSocketHandler webSocketHandler(){        return new SpringWebSocketHandler();    }}

 第三步:继承WebSocketHandler对象。该对象提供了客户端连接,关闭,错误,发送等方法,重写这几个方法即可实现自定义业务逻辑

package com.quicksand.push;import java.io.IOException;import java.util.ArrayList;import org.apache.log4j.Logger;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;public class SpringWebSocketHandler extends TextWebSocketHandler {    private static final ArrayList
users;//这个会出现性能问题,最好用Map来存储,key用userid private static Logger logger = Logger.getLogger(SpringWebSocketHandler.class); static { users = new ArrayList
(); } public SpringWebSocketHandler() { // TODO Auto-generated constructor stub } /** * 连接成功时候,会触发页面上onopen方法 */ public void afterConnectionEstablished(WebSocketSession session) throws Exception { // TODO Auto-generated method stub System.out.println("connect to the websocket success......当前数量:"+users.size()); users.add(session); //这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户 //TextMessage returnMessage = new TextMessage("你将收到的离线"); //session.sendMessage(returnMessage); } /** * 关闭连接时触发 */ public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { logger.debug("websocket connection closed......"); String username= (String) session.getAttributes().get("WEBSOCKET_USERNAME"); System.out.println("用户"+username+"已退出!"); users.remove(session); System.out.println("剩余在线用户"+users.size()); } /** * js调用websocket.send时候,会调用该方法 */ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); } public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){session.close();} logger.debug("websocket connection closed......"); users.remove(session); } public boolean supportsPartialMessages() { return false; } /** * 给某个用户发送消息 * * @param userName * @param message */ public void sendMessageToUser(String userName, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get("WEBSOCKET_USERNAME").equals(userName)) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } break; } } } /** * 给所有在线用户发送消息 * * @param message */ public void sendMessageToUsers(TextMessage message) { for (WebSocketSession user : users) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } }}

第四步:继承HttpSessionHandshakeInterceptor对象。该对象作为页面连接websocket服务的拦截器,代码如下:

package com.quicksand.push;import java.util.Map;import javax.servlet.http.HttpSession;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 org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;/** * WebSocket拦截器 * @author WANG * */public class SpringWebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {    @Override    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,            Map
attributes) throws Exception { // TODO Auto-generated method stub System.out.println("Before Handshake"); if (request instanceof ServletServerHttpRequest) { ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request; HttpSession session = servletRequest.getServletRequest().getSession(false); if (session != null) { //使用userName区分WebSocketHandler,以便定向发送消息 String userName = (String) session.getAttribute("SESSION_USERNAME"); if (userName==null) { userName="default-system"; } attributes.put("WEBSOCKET_USERNAME",userName); } } return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { // TODO Auto-generated method stub super.afterHandshake(request, response, wsHandler, ex); }}

第5步 让SpringWebSocketConfig配置类随spring容器启动 spring文件中加入如下代码:

 

-------------------------------------------------------------------------到这里就算完成啦 下面准备测试-------------------------------------------------------------

1.定义一个控制器用来做连接标识和发送消息

package com.quicksand.controller;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.socket.TextMessage;import com.quicksand.push.SpringWebSocketHandler;@Controllerpublic class WebsocketController {    @Bean//这个注解会从Spring容器拿出Bean    public SpringWebSocketHandler infoHandler() {        return new SpringWebSocketHandler();    }    @RequestMapping("/websocket/login")    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws Exception {        String username = request.getParameter("username");        System.out.println(username+"登录");        HttpSession session = request.getSession(false);        session.setAttribute("SESSION_USERNAME", username);        //response.sendRedirect("/quicksand/jsp/websocket.jsp");        return new ModelAndView("websocket");    }    @RequestMapping("/websocket/send")    @ResponseBody    public String send(HttpServletRequest request) {        String username = request.getParameter("username");        infoHandler().sendMessageToUser(username, new TextMessage("你好,测试!!!!"));        return null;    }}

 

2.建立登录页面

 

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%>

Hello World!

登录名:

 

3.建立发消息页面

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%>
Insert title here

   window.close=function()

   {
     websocket.onclose();
   }

请输入:

转载于:https://my.oschina.net/zhougui/blog/1550456

你可能感兴趣的文章
第20章 数据库操作----JDBC概述
查看>>
js 取父级 页面上的元素
查看>>
XQuery的sql:variable() 函数
查看>>
阿里、有道科大讯飞齐为荣耀Magic2打call,透露YOYO想不到的技能
查看>>
微服务在微信的架构实践
查看>>
HTTP Header简介
查看>>
Java并发编程----阻塞队列
查看>>
极简教程: 使用 matplotlib 绘制 GIF 动图
查看>>
数据库分片(Database Sharding)详解
查看>>
技术风险防控平台:打造金融交易系统的故障免疫能力
查看>>
怎样把酷狗音乐wav转化成高品质的MP3格式?
查看>>
浅谈算法学习
查看>>
前端知识点——图片
查看>>
thinkphp源码分析(三)—自动加载篇(Loader的分析)
查看>>
Blink 真香
查看>>
一块听听:Mixin 主网上线语音直播文字稿
查看>>
brew安装错误brew Error: /usr/local must be writable!
查看>>
可应用于实际的14个NLP突破性研究成果(三)
查看>>
[LeetCode] 41. First Missing Positive
查看>>
阿里如何将“高峰前扩容、高峰后缩容”的梦想照进现实?
查看>>