前言
&nsbp; 最近在搞一个websocket的小尝试,打算用在前后端分离的项目上,先拿后端做个尝试,特此记录下。
正文
一、引入maven 依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
二、准备常量类
package com.dmsdbj.itoo.utils;
public class Constant {
//webSocket相关配置
//链接地址
public static String WEBSOCKETPATHPERFIX = "/ws-push";
public static String WEBSOCKETPATH = "/endpointWisely";
//消息代理路径
public static String WEBSOCKETBROADCASTPATH = "/topic";
//前端发送给服务端请求地址
public static final String FORETOSERVERPATH = "/welcome";
//服务端生产地址,客户端订阅此地址以接收服务端生产的消息
public static final String PRODUCERPATH = "/topic/getResponse";
//点对点消息推送地址前缀
public static final String P2PPUSHBASEPATH = "/user";
//点对点消息推送地址后缀,最后的地址为/user/用户识别码/msg
public static final String P2PPUSHPATH = "/msg";
}
三、定义两个消息实体
//接收前端消息实体
public class WiselyMessage {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//后台发送消息实体
private String responseMessage;
public WiselyResponse(String responseMessage){
this.responseMessage = responseMessage;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
四、配置websocket
@Configuration
// 开始支持@MessageMapping,就像是使用@requestMapping一样。
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
//注册一个Stomp的节点(endpoint),并指定使用SockJS协议
stompEndpointRegistry.addEndpoint(Constant.WEBSOCKETPATH). setAllowedOrigins("*").withSockJS();
}
// 配置消息
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//服务端发送消息给客户端的域,多个用逗号隔开
registry.enableSimpleBroker(Constant.WEBSOCKETBROADCASTPATH, Constant.P2PPUSHBASEPATH);
//定义一对一推送的时候前缀
registry.setUserDestinationPrefix(Constant.P2PPUSHBASEPATH);
//定义websoket前缀---服务端地址前缀
registry.setApplicationDestinationPrefixes(Constant.WEBSOCKETPATHPERFIX);
}
}
五、控制器类
@RequestMapping("/onlineExam")
@Controller
public class OnlineExamController {
@Autowired
private OnlineExamFacade onlineExamFacade;
// 配置访问subws.html
@RequestMapping(value={"subws"},method=RequestMethod.GET)
public String subws(){
return"subws";
}
// 配置访问sendws.html
@RequestMapping(value={"sendws"},method=RequestMethod.GET)
public String sendws(){
return"sendws";
}
//订阅消息测试--添加用户信息
@GetMapping("/insert")
@ResponseBody
public boolean insertUser(String userId){
return onlineExamFacade.insertUser(userId);
}
@Autowired
private SimpMessagingTemplate template;
//广播发送消息
@MessageMapping(Constant.FORETOSERVERPATH)//@MessageMapping和@RequestMapping功能类似,用于设置URL映射地址,浏览器向服务器发起请求,需要通过该地址。
public WiselyResponse say(WiselyMessage message) throws Exception {
// 所有用户
List<String> userId = onlineExamFacade.send2Users();
userId.forEach(s->{
template.convertAndSendToUser(s.toString(), Constant.P2PPUSHPATH, new WiselyResponse(message.getName()));
});
return null;
}
六、HTML 页面(部分代码)
//***************subws.html*******************
<!DOCTYPE html>
<div>
<div>
<button id="connect" onclick="connect();">连接</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的userId</label><input type="text" id="userId" />
<button id="subMsg" onclick="subMsg();">订阅消息</button>
<p id="response"></p>
<p id="response1"></p>
</div>
</div>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script th:inline="javascript">
var stompClient = null;
//此值有服务端传递给前端,实现方式没有要求
//var userId = [[${userId}]];
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
}
function connect() {
// 注意 SockJS()中传入的地址 一定要正确
var socket = new SockJS('/exam-web/endpointWisely');
stompClient = Stomp.over(socket);//2创建STOMP协议的webSocket客户端。
stompClient.connect({}, function(frame) {//3连接webSocket的服务端。
setConnected(true);
console.log('开始进行连接Connected: ' + frame);
});
}
//订阅消息
function subMsg() {
var userId = $('#userId').val();
console.log(userId);
$.ajax({
type: 'GET',
url: '/exam-web/onlineExam/insert?userId='+userId,
success: function (data) {
console.log(data);
//4通过stompClient.subscribe()订阅服务器的目标是'/user/' + userId + '/msg'接收一对一的推送消息,其中userId由服务端传递过来,用于表示唯一的用户,通过此值将消息精确推送给一个用户
stompClient.subscribe('/user/' + userId + '/msg', function(respnose){
console.log(respnose); showResponse1(JSON.parse(respnose.body).responseMessage);
});
}
});
}
</script>
</body>
</html>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script th:inline="javascript">
var stompClient = null;
//此值有服务端传递给前端,实现方式没有要求
//var userId = [[${userId}]];
var userId = 'd892bf12bf7d11e793b69c5c8e6f60fb';
……
// 建立连接方法
function connect() {
var socket = new SockJS('/exam-web/endpointWisely');
stompClient = Stomp.over(socket);//2创建STOMP协议的webSocket客户端。
stompClient.connect({}, function(frame) {//3连接webSocket的服务端。
setConnected(true);
console.log('开始进行连接Connected: ' + frame);
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
// 输入名字之后,点击发送消息
function sendName() {
var name = $('#name').val();
console.log(name);
//通过stompClient.send()向地址为"/welcome"的服务器地址发起请求,与@MessageMapping里的地址对应。因为我们配置了registry.setApplicationDestinationPrefixes(Constant.WEBSOCKETPATHPERFIX);所以需要增加前缀/ws-push/
stompClient.send("/ws-push/welcome", {}, JSON.stringify({ 'name': name }));
}
七、效果展示
接收端:先连接,连接成功后,‘订阅’消息成功后,收到了发送端的‘你好’消息
发送端: 发送了‘你好’消息
八、遇到的问题 :lost connection to http://localhost:8089/endpointWisely
解决:
function connect() {
//*********错误的写法************/
//var socket = new SockJS('/endpointWisely'); //1连接SockJS的endpoint是“endpointWisely”,与后台代码中注册的endpoint要一样。
//*********正确的写法************/
var socket = new SockJS('/exam-web/endpointWisely');
stompClient = Stomp.over(socket);//2创建STOMP协议的webSocket客户端。
总结
通过这次实践对websock有了一点了解,下一步准备实现前后端分离的websocket通信。
感谢丽同、建敏、和涛哥的支持和帮助!