写在前边的话:此项目基于springboot1.5.2版本,dubbo使用2.8.4,使用thymleaf为渲染模板,jdk1.7,如springboot为2.0以上版本,请使用jdk1.8,相关接口实现也均已变更。【本人亲测可用,附源码下载地址,可自行下载】
以下代码编辑器格式有点乱, 拷贝后自行格式化
二. 相关代码
0. 变量集合
package com.song.config;/** * 常量 * * @author songshijun * @time 2018-03-27 */public class Constants {/** * socket常量 */ public static class WebSocket{public static StringWEBSOCKETPATHPERFIX ="/send";public static StringREGISTRY_MSGCENTER ="/registry/msgcenter";//广播中心地址 /** 点对点 */ public static final StringP2PPUSHBASEPATH ="/p2p";//点对点消息推送地址前缀 public static final StringP2PPUSHPATH ="/msg";//点对点消息推送地址后缀,地址: /user/用户识别码/msg /** 广播地址 */ public static final StringMSGMAPPING_BROADCAST="/broadcast";//消息代理路径 public static final StringRESPONSE_BROADCAST ="/broadcast/response";//客户端订阅地址接收服务端消息 }}
1. websocket相关配置
public class WebSocketConfigextends AbstractWebSocketMessageBrokerConfigurer {@Override public void registerStompEndpoints(StompEndpointRegistry arg0) { arg0.addEndpoint(WebSocket.REGISTRY_MSGCENTER).withSockJS(); }@Override public void configureMessageBroker(MessageBrokerRegistry registry) {//服务端发送消息给客户端的域,多个用逗号隔开 registry.enableSimpleBroker(WebSocket.MSGMAPPING_BROADCAST, WebSocket.P2PPUSHBASEPATH); registry.setUserDestinationPrefix(WebSocket.P2PPUSHBASEPATH);//定义一对一推送的时候前缀 registry.setApplicationDestinationPrefixes(WebSocket.WEBSOCKETPATHPERFIX);//客户端消息推送路由前缀 }}
2. 消息实体
WiselyMessage.java
package com.song.model;/** * 发送消息实体类 * * @author songshijun * @time 2018-03-27 */public class WiselyMessage {private Stringname;private StringuserId;public String getName() {return name; }public void setName(String name) {this.name = name; }public String getUserId() {return userId; }public void setUserId(String userId) {this.userId = userId; }}
WiselyResponse.java
package com.song.model;/** * 返回消息实体类 * * @author songshijun * @time 2018-03-27 */public class WiselyResponse {private StringresponseMessage;public String getResponseMessage() {return responseMessage; }public void setResponseMessage(String responseMessage) {this.responseMessage = responseMessage; }}
3. 消息发送接口
package com.song.service;import com.song.model.WiselyResponse;import java.util.List;/** * 消息发送接口 * * @author songshijun * @time 2018-03-27 */public interface WebsocketService {void send2Users(List users, WiselyResponse msg);}
4. 消息接口实现类
package com.song.serviceimpl;import static com.song.config.Constants.WebSocket;import com.song.model.WiselyResponse;import com.song.service.WebsocketService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.messaging.simp.SimpMessagingTemplate;import org.springframework.stereotype.Service;import java.util.List;/** * 消息发送实体类 * * @author songshijun * @time 2018-03-27 */@Servicepublic class WebsocketServiceImplimplements WebsocketService{@Autowired private SimpMessagingTemplatetemplate;/** * 发送给指定用户 * * @param users * @param msg */ @Override public void send2Users(List users, WiselyResponse msg) {for(String user:users){template.convertAndSendToUser(user, WebSocket.P2PPUSHPATH, msg); } }}
5. websocket测试主页
html><html xmlns:th="http://www.thymleaf.org"><head><meta charset="UTF-8"/><title th:text="'当前广播站点'+${userId}">title><link rel="stylesheet" th:href="@{/css/app/websocketBroadcast.css}"/>head><body><div><button id="connect" onclick="SocketBroad.connect()">连接button><button id="disconnect" onclick="SocketBroad.disconnect();">断开连接button>div><div id="conversationDiv"><div class="main"><div>广播发送 --> <span style="margin-top:50px">MSG SEND:<input type="text" id="broadcast" placeholder="请输入广播发布的信息"/>span><span><button onclick="SocketBroad.sendBroadcast();">广播发送button>span><br/>点对点发送 --> <span style="margin-top:50px">MSG SEND:<input type="text" id="p2p" placeholder="请输入点对点发布的信息"/><input type="text" id="toUser" placeholder="请输入要推送的用户ID"/>span><span><button onclick="SocketBroad.sendP2p();">点对点发送button>span><br/><br/>消息推送页面显示 --> <span style="margin-top:50px">Receive the broadcast message:span><span><p id="response">p>span><span style="margin-top:50px">Receive the P2P message:span><span><p id="response1">p>span>div>div>div><script type="text/javascript" th:src="@{/js/common/stomp.min.js}">script><script type="text/javascript" src="/js/common/sockjs.min.js">script><script type="text/javascript" src="/js/common/jquery-1.8.3.min.js">script><script type="text/javascript" src="/js/app/socketBroad.js">script><script th:inline="javascript">var userId= [[${userId}]];script>body>html>
6. 页面逻辑js
var SocketBroad = (function($){var stompClient =null;/** * 连接设置 * * @param connected */ var setConnected =function (connected) {document.getElementById('connect').disabled = connected;document.getElementById('disconnect').disabled = !connected;document.getElementById('conversationDiv').style.visibility = connected ?'visible' :'hidden'; $('#response').html(); }/** * 建立长连接 */ var connect =function () {var socket =new SockJS('/registry/msgcenter');stompClient =Stomp.over(socket);stompClient.connect({},function(frame) {setConnected(true);console.log('Connected:' + frame);//地址订阅 stompClient.subscribe('/broadcast/response',function(response) {console.log(response)showResponse(JSON.parse(response.body).responseMessage); });stompClient.subscribe('/p2p/' +userId +'/msg',function(respnose){console.log(respnose);showResponse1(JSON.parse(respnose.body).responseMessage); }); }); }/** * 断开连接 */ var disconnect =function () {if (stompClient !=null) {stompClient.disconnect(); }setConnected(false);console.log("Disconnected"); }/** * 发布广播消息 */ var sendBroadcast =function () {var name = $('#broadcast').val();stompClient.send("/send/broadcast", {},JSON.stringify({name:name})); }var sendP2p =function(){var name = $('#p2p').val();var userId = $('#toUser').val();if(!userId){alert("请输入要推送的用户ID");return; }stompClient.send("/send/p2p", {},JSON.stringify({name:name,userId:userId})); }/** * 渲染接接收的广播消息 * @param message */ var showResponse =function (message) {var response = $('#response');response.html(message); }var showResponse1 =function (message) {var response = $("#response1");response.html(message); }return {connect:connect,disconnect:disconnect,sendBroadcast:sendBroadcast,sendP2p:sendP2p }})(jQuery)$(function(){SocketBroad.disconnect();})
源码下载地址:【该地址同步本人CSDN账号非盗用】https://download.csdn.net/download/u011127348/10311990