服务端开启一个websocket,其他人的加入只需修改网页socket链接既可以
spring-mvc.xml
<context:component-scan base-package="com.milanosoft.RCS.web.webSocket.config" /> <context:component-scan base-package="com.milanosoft.RCS.web.webSocket.hndler"> </context:component-scan> <context:component-scan base-package="com.milanosoft.RCS.web.webSocket.interceptor"> </context:component-scan>
1 拦截
import java.util.Map; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; /** * 模拟多账号登陆推送,生产环境根据请求reqId做为判断 * */ @Component public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { System.out.println("Before Handshake"); String merchantId = ((ServletServerHttpRequest)request).getServletRequest().getParameter ("userId"); String userName = ((ServletServerHttpRequest)request).getServletRequest().getParameter ("userName"); attributes.put("userId", merchantId); attributes.put("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); } }
2 socket处理类
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; /** * * @author zxn * userName 在这里充当渠道 */ @Component public class SystemWebSocketHandler implements WebSocketHandler { private static final Map<Long,List<WebSocketSession>> users; static { users = new HashMap<Long,List<WebSocketSession>>(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { System.out.println("connect to the websocket success......"); Object userId = session.getAttributes().get("userId"); String userName = session.getAttributes().get("userName").toString(); Long id = Long.valueOf(userId.toString()); //上线提示 for(Map.Entry<Long,List<WebSocketSession>> user:users.entrySet()){ for(WebSocketSession userSocket :user.getValue()){ if(userSocket.isOpen()){ userSocket.sendMessage(new TextMessage(userName+"已上线")); } } } //保存socket if(users.get(id)!=null){ users.get(id).add(session); }else{ List<WebSocketSession> socketList= new ArrayList<>(); socketList.add(session); users.put(id,socketList); } session.sendMessage(new TextMessage("成功连接服务器")); } @Override public void handleMessage(WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception { Object userId = wss.getAttributes().get("userId"); Long id = Long.valueOf(userId.toString()); String userName = wss.getAttributes().get("userName").toString(); TextMessage returnMessage = new TextMessage("用户"+userName+"对大家说:"+wsm.getPayload()); for(Map.Entry<Long,List<WebSocketSession>> user:users.entrySet()){ //userId代表用户,userName实际模拟多端登陆 /* if(user.getKey().intValue()==id.intValue()) continue; for(WebSocketSession userSocket :user.getValue()){ if(userSocket.isOpen()){ userSocket.sendMessage(returnMessage); } }*/ //为了在本机测试做的模拟;消息不发给自己 for(WebSocketSession userSocket :user.getValue()){ if(userSocket.isOpen()){ String name = userSocket.getAttributes().get("userName").toString(); if(name.equals(userName)){ continue; } userSocket.sendMessage(returnMessage); } } } } @Override public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception { //出现异常关闭socket连接 if(wss.isOpen()){ wss.close(); } /* System.out.println("websocket connection closed......"); Object userId = wss.getAttributes().get("userId"); Long id = Long.valueOf(userId.toString()); //具体某一个socket users.remove(id);*/ } @Override public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception { System.out.println("websocket connection closed......"); Object userId = wss.getAttributes().get("userId"); Long id = Long.valueOf(userId.toString()); String userName = wss.getAttributes().get("userName").toString(); //具体某一个socket List<WebSocketSession> list = users.get(id); if(list!=null && list.size()>0){ for(WebSocketSession se:list){ //判断渠道移除 String name = se.getAttributes().get("userName").toString(); if(name.equals(userName)){ list.remove(se); break; } } } //通知某个用户下线 if(list!=null && list.size()>0){ for(WebSocketSession se:list){ se.sendMessage(new TextMessage(userName+"已下线")); } } //socket全部失效 if(list.size()==0){ users.remove(id); } } @Override public boolean supportsPartialMessages() { return false; } }
3 socket的配置
import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; 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 com.milanosoft.RCS.web.webSocket.interceptor.HandshakeInterceptor; import org.springframework.context.annotation.Bean; @Configuration @EnableWebMvc @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { public WebSocketConfig() { } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(systemWebSocketHandler(), "/websck").addInterceptors(new HandshakeInterceptor()); System.out.println("registed!"); registry.addHandler(systemWebSocketHandler(), "/sockjs/websck/info").addInterceptors(new HandshakeInterceptor()) .withSockJS(); } @Bean public WebSocketHandler systemWebSocketHandler() { //return new InfoSocketEndPoint(); return new SystemWebSocketHandler(); } }
4 模拟测试页面
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title> <style type="text/css"> #connect-container { float: left; width: 400px } #connect-container div { padding: 5px; } #console-container { float: left; margin-left: 15px; width: 400px; } #console { border: 1px solid #CCCCCC; border-right-color: #999999; border-bottom-color: #999999; height: 170px; overflow-y: scroll; padding: 5px; width: 100%; } #console p { padding: 0; margin: 0; } </style> <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script> <script type="text/javascript"> var ws = null; var url = null; var transports = []; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('echo').disabled = !connected; } function connect() { if (!url) { alert('Select whether to use W3C WebSocket or SockJS'); return; } //ws = (url.indexOf('sockjs') != -1) ?new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url); if ('WebSocket' in window) { ws= new WebSocket("ws://localhost:8084/websck?userId=1&userName=小曾"); }else { ws = new SockJS("http://localhost:8084/sockjs/websck?userId=1&userName=小曾"); } //websocket = new SockJS("http://localhost:8084/SpringWebSocketPush/sockjs/websck"); ws.onopen = function () { alert('open'); setConnected(true); //log('Info: connection opened.'); }; ws.onmessage = function (event) { alert('Received:' + event.data); log('Received: ' + event.data); }; ws.onclose = function (event) { setConnected(false); log('Info: connection closed.'); log(event); }; } function disconnect() { if (ws != null) { ws.close(); ws = null; } setConnected(false); } function echo() { if (ws != null) { var message = document.getElementById('message').value; log('Sent: ' + message); ws.send(message); } else { alert('connection not established, please connect.'); } } function updateUrl(urlPath) { if (urlPath.indexOf('sockjs') != -1) { url = urlPath; document.getElementById('sockJsTransportSelect').style.visibility = 'visible'; } else { if (window.location.protocol == 'http:') { url = 'ws://' + window.location.host + urlPath; } else { url = 'wss://' + window.location.host + urlPath; } document.getElementById('sockJsTransportSelect').style.visibility = 'hidden'; } } function updateTransport(transport) { alert(transport); transports = (transport == 'all') ? [] : [transport]; } function log(message) { var console = document.getElementById('console'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.appendChild(document.createTextNode(message)); console.appendChild(p); while (console.childNodes.length > 25) { console.removeChild(console.firstChild); } console.scrollTop = console.scrollHeight; } </script> </head> <body> <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable Javascript and reload this page!</h2></noscript> <div> <div id="connect-container"> <input id="radio1" type="radio" name="group1" οnclick="updateUrl('/websocket');"> <label for="radio1">W3C WebSocket</label> <br> <input id="radio2" type="radio" name="group1" οnclick="updateUrl('/sockjs/websocket');"> <label for="radio2">SockJS</label> <div id="sockJsTransportSelect" style="visibility:hidden;"> <span>SockJS transport:</span> <select οnchange="updateTransport(this.value)"> <option value="all">all</option> <option value="websocket">websocket</option> <option value="xhr-polling">xhr-polling</option> <option value="jsonp-polling">jsonp-polling</option> <option value="xhr-streaming">xhr-streaming</option> <option value="iframe-eventsource">iframe-eventsource</option> <option value="iframe-htmlfile">iframe-htmlfile</option> </select> </div> <div> <button id="connect" οnclick="connect();">Connect</button> <button id="disconnect" disabled="disabled" οnclick="disconnect();">Disconnect</button> </div> <div> <textarea id="message" style="width: 350px">Here is a message!</textarea> </div> <div> <button id="echo" οnclick="echo();" disabled="disabled">Echo message</button> </div> </div> <div id="console-container"> <div id="console"></div> </div> </div> </body> </html>