博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring 搭建 websocket
阅读量:6291 次
发布时间:2019-06-22

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

hot3.png

maven依赖

pool.xml

4.0.0
springws
springws
1.0-SNAPSHOT
org.springframework
spring-context
4.3.9.RELEASE
org.springframework
spring-webmvc
4.3.9.RELEASE
org.springframework
spring-websocket
4.3.9.RELEASE

web.xml

springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/springmvc-servlet.xml
springmvc
/

springmvc-servlet.xml

text/plain;charset=UTF-8

显示的控制器:

indexController.java

package com.chen;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;/** * Created by yuerwang on 2017/7/6. */@Controller@RequestMapping("/Index")public class IndexController {    @RequestMapping("/index")    public void index(ModelMap mp){         mp.put("chen",123);    }}

显示页面

index.jsp

<%--  Created by IntelliJ IDEA.  Date: 2017/7/6  Time: 14:39  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>  测试  ${chen}

处理websocket

WebsocketConfig.java

package com.chen.conf;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;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@EnableWebSocketpublic class WebsocketConfig implements WebSocketConfigurer {    @Override    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {        registry.addHandler(chatMessageHandler(),"/websocket/chatMessageServer.do").addInterceptors(new ChatHandshakeInterceptor());        registry.addHandler(chatMessageHandler(), "/sockjs/chatMessageServer.do").addInterceptors(new ChatHandshakeInterceptor()).withSockJS();    }    @Bean    public TextWebSocketHandler chatMessageHandler(){        return new ChatMessageHandler();    }}

ChatHandshakeInterceptor.java

package com.chen.conf;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.HandshakeInterceptor;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;import javax.servlet.http.HttpSession;import java.util.Map;/** * Created by yuerwang on 2017/7/6. */public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {    @Override    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map
attributes) throws Exception { 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(Constants.SESSION_USERNAME); if (userName==null) { userName="default-system"; } attributes.put(Constants.WEBSOCKET_USERNAME,userName); } } return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { System.out.println("After Handshake"); super.afterHandshake(request, response, wsHandler, ex); }}

ChatMessageHandler.java(主要处理逻辑)

package com.chen.conf;import java.io.IOException;import java.util.ArrayList;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;/** * Created by yuerwang on 2017/7/6. */public class ChatMessageHandler extends TextWebSocketHandler{    private static final ArrayList
users;//这个会出现性能问题,最好用Map来存储,key用userid static { users = new ArrayList
(); } public ChatMessageHandler() { // TODO Auto-generated constructor stub } /** * 连接成功时候,会触发UI上onopen方法 */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("connect to the websocket success......"); users.add(session); //这块会实现自己业务,比如,当用户登录后,会把离线消息推送给用户 TextMessage returnMessage = new TextMessage("你将收到的消息"); session.sendMessage(returnMessage); } /** * 在UI在用js调用websocket.send()时候,会调用该方法 */ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { for (WebSocketSession user:users){ System.out.println(user); } System.out.println("发送的是:"+message); //回复群体消息  //sendMessageToUsers(new TextMessage("全体消息:"+message.getPayload()));  //回复发送者消息        session.sendMessage(message); super.handleTextMessage(session, message); } /** * 给某个用户发送消息 * * @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; } } } /** * 给所有在线用户发送消息 * * @param message */ public void sendMessageToUsers(TextMessage message) { for (WebSocketSession user : users) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){ session.close(); } users.remove(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { users.remove(session); } @Override public boolean supportsPartialMessages() { return false; }}

Constants.java

package com.chen.conf;public class Constants {   public static final String WEBSOCKET_USERNAME = "ws_user";     public static final String SESSION_USERNAME = "se_user";}

转载于:https://my.oschina.net/u/2528821/blog/1186743

你可能感兴趣的文章
[SilverLight]DataGrid实现批量输入(like Excel)(补充)
查看>>
秋式广告杀手:广告拦截原理与杀手组织
查看>>
翻译 | 摆脱浏览器限制的JavaScript
查看>>
闲扯下午引爆乌云社区“盗窃”乌云币事件
查看>>
02@在类的头文件中尽量少引入其他头文件
查看>>
JAVA IO BIO NIO AIO
查看>>
input checkbox 复选框大小修改
查看>>
BOOT.INI文件参数
查看>>
vmstat详解
查看>>
新年第一镖
查看>>
unbtu使用笔记
查看>>
OEA 中 WPF 树型表格虚拟化设计方案
查看>>
Android程序开发初级教程(一) 开始 Hello Android
查看>>
使用Gradle打RPM包
查看>>
“我意识到”的意义
查看>>
淘宝天猫上新辅助工具-新品填表
查看>>
再学 GDI+[43]: 文本输出 - 获取已安装的字体列表
查看>>
nginx反向代理
查看>>
操作系统真实的虚拟内存是什么样的(一)
查看>>
hadoop、hbase、zookeeper集群搭建
查看>>