1.引入依赖
1.1 引入websocket依赖
1.2 引入thymeleaf模板引擎依赖
<!-- springboot websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.webSocket配置类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
// 设置socket连接
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/testSocket")
//.setAllowedOrigins("*")
//解决跨域问题
.setAllowedOriginPatterns("*")
.withSockJS();
}
// 设置发布订阅的主题
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/top");
}
}
2.1配置说明:
前端与后台服务建立连接的路径,如:http://localhost:8080/testSocket
stompEndpointRegistry.addEndpoint("/testSocket")
连接的路由配置,只有以topic或者top开头的路径才会被订阅
registry.enableSimpleBroker("/topic", "/top");
3.应用控制器
@Controller
public class WebsocketController {
@Autowired
private SimpMessagingTemplate simpMessagingTemplate;
/**
* 服务端想客户端发送消息
*/
@RequestMapping("/send01")
@ResponseBody
public String send() {
// 订阅主题,只有订阅了这个主题的连接才会接收消息
String topic = "/topic/businessUserId/162";
// 消息内容
String message = "你好呀";
simpMessagingTemplate.convertAndSend(topic, message);
return "调用成功!";
}
/**
* 客户端向客户端发送消息
*/
@MessageMapping("/test")
@SendTo("/topic/businessUserId/162")
@ResponseBody
public String call(String msg) {
System.out.println(msg);
return msg;
}
@RequestMapping("/socketPage")
public String socketPage() {
return "socket";
}
}
4.前端HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webSocket</title>
</head>
<body>
<div>
<h2>Socket 网络实时交互测试</h2>
<div>
<button id="connect" onclick="connect();">建立连接</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label>
<input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var stompClient = null;
$(function(){
connect();
});
function setConnected(connected) {
$("#connect").attr("disabled", connected);
$("#disconnect").attr("disabled", !connected);
if (connected) {
$("#conversationDiv").show();
}else{
$("#conversationDiv").hide();
}
$("#response").html("");
}
//this line.
function connect() {
var socket = new SockJS("http://localhost:8080/testSocket");
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
// console.log('Connected: ' + frame);
// stompClient.subscribe('/top/test', function(frame){
stompClient.subscribe('/topic/businessUserId/162', function(frame){
//showGreeting(JSON.parse(greeting.body).content);
console.info(frame);
showGreeting(frame.body);
});
});
}
function sendName() {
var name = $("#name").val();
stompClient.send("/test", {}, name);
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function showGreeting(message) {
$("#response").append("<tr><td>" + message + "</td></tr>");
}
</script>
</html>
5.项目架构图
9b1d2abf43e3674fa5ea806cf3b5e1b.png6.调试
6.1启动项目后访问地址:http://localhost:8080/socketPage
点击send发送消息,只要保证都订阅的都是一个topic,就能看到消息
7.由服务端向客户端发送消息
7.1 调用后台接口 http://localhost:8080/send01,此时会使用simpMessagingTemplate.convertAndSend(topic, message);方法,向指定的topic发送一条消息,那么订阅了这个topic的就可以实时的看到这个消息,测试一下
微信图片_20210508160646.png 微信图片_20210508160724.png
网友评论