pom.xml需要添加部分
<!-- stomp -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- stomp 第三方代理 -->
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-net</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.0.30.Final</version>
</dependency>
<dependency>
<groupId>fr.jcgay.send-notification</groupId>
<artifactId>send-notification</artifactId>
<version>0.11.0</version>
</dependency>
配置config
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//为/marcopolo 开启sockJS功能
registry.addEndpoint("/marcopolo").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// super.configureMessageBroker(registry);
//启用代理中继 如RabbitMQ或activeMQ
// registry.enableStompBrokerRelay("/queue","/topic");
//简单的基于内存的代理
registry.enableSimpleBroker("/queue","/topic");
registry.setApplicationDestinationPrefixes("/app");
//一对一主题前缀 /user 默认也为user
// registry.setUserDestinationPrefix("/user");
}
controller
@SendTo("/topic/go") 指定返回的广播
@SendToUser("/queue/notifications")指定返回的用户
Principal 为当前登陆的用户
template.convertAndSendToUser(userid, "/queue/message", alert); 返回给指定的目标 适合已通过登陆认证的
@Controller
public class MarcoController {
public SimpMessagingTemplate template;
@Autowired
public MarcoController(SimpMessagingTemplate template) {
super();
this.template = template;
}
@MessageMapping("/marcogo")
@SendTo("/topic/go")
public Alert handle(Alert alert) {
System.out.println(alert.toString());
Alert a = new Alert();
a.setName(alert.toString());
return a;
}
@MessageMapping("/sendToUser")
public void sendToUser(Alert alert) {
System.out.println("sendToUser 接收到信息:"+alert.toString());
// 发送给指定用户
if (StringUtils.isNotBlank(alert.getId()))
template.convertAndSendToUser(alert.getId(), "/queue/message", alert);
}
@SubscribeMapping("/marcogo")
@SendToUser("/queue/notifications")
public Alert handleSubscription(Principal principal) {
System.out.println("客户端已连接!");
Alert alert = new Alert();
alert.setName(principal.getName()+"服务器连接成功!");
return alert;
}
}
前端JS
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
<script type="text/javascript">
/* var url = 'http://' + window.location.host + '/spittr/marcopolo';
//var sock = new WebSocket(url);
//var url = 'marco';
var sock = new SockJS(url);
var stomp = Stomp.over(sock);
var payload = JSON.stringify({
"id" : "123",
'name' : "adfasdf"
});
stomp.connect({}, function(frame) {
console.log('Connected');
stomp.subscribe('/topic/marcogo', function(message) {
console.log(message);
var json = JSON.parse(message.body);
});
stomp.send("/marcogo", {}, payload);
}); */
</script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible'
: 'hidden';
document.getElementById('response').innerHTML = '';
}
function sendName() {
var name = document.getElementById('name').value;
var toid = $("#toid").val();
//如果没有toid 则广播这条信息
if (toid == null || toid == undefined || toid == "") {
stompClient.send("/app/marcogo", {}, JSON.stringify({
'id' : $("#toid").val(),
'name' : name
}));
} else {
stompClient.send("/app/sendToUser", {}, JSON.stringify({
'id' : $("#toid").val(),
'name' : name
}));
}
}
function connectAny() {
var socket = new SockJS("<c:url value='/marcopolo'/>");
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/go', function(data) {
showGreeting('/topic/go:' + JSON.parse(data.body).name);
});
//接收 指定 userid的消息
stompClient.subscribe('/user/queue/message', function(data) {
showGreeting("接收到的内容:" + JSON.parse(data.body).name);
});
stompClient.subscribe('/app/marcogo', function(data) {
console.log('初始化服务!');
showGreeting(JSON.parse(data.body).name);
});
//接收指定消息
stompClient.subscribe('/user/queue/notifications', function(data) {
showGreeting("单独接收到消息:" + JSON.parse(data.body).name);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body>
<noscript>
<h2 style="color: #ff0000">Seems your browser doesn't support
Javascript! Websocket relies on Javascript being enabled. Please
enable Javascript and reload this page!</h2>
</noscript>
<div>
<div>
<button id="connectAny" οnclick="connectAny();">连接</button>
<button id="disconnect" disabled="disabled" οnclick="disconnect();">关闭</button>
</div>
<div>
<label>自己的ID</label><input type="text" id="userid" />
</div>
<div id="conversationDiv">
<label>发送的对方ID</label><input type="text" id="toid" /> <label>内容</label><input
type="text" id="name" />
<button id="sendName" οnclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
通过上面的简单配置就可以实现 消息的发送,接收,订阅
在来一种不用登陆就可以给指定用户发消息的配置
config中
registry.enableSimpleBroker("/queue","/topic","/user");
要指定放回的目标用户
template.convertAndSendToUser(alert.getId(), "/message", alert);
前端js订阅的地址
//接收 指定 userid的消息
stompClient.subscribe('/user/'+$("#userid").val()+'/message', function(data) {
showGreeting("接收到的内容:" + JSON.parse(data.body).name);
});
这样 不用登陆 也能更加自己设定的id 接收指定信息了 吼吼!!