https://www.jianshu.com/p/60799f1356c5
https://www.jianshu.com/p/8500ad65eb50
这上面已经说得很详细的。以下简单总结,便于理解。查阅过程中可对照以上两链接中的详细内容。
1.添加依赖
2.配置。用java类
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
//addEndpoint,客户端通过这个建立连接
//withSockJS,开启SockJS支持
registry.addEndpoint("/socket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//给客户端发送消息前缀
registry.enableSimpleBroker("/topic");
//接收客户端消息的前缀
registry.setApplicationDestinationPrefixes("/app");
}
}
3.服务器端接收与发送
@Controller
public class GreetingController {
@Resource
private SimpMessagingTemplate simpMessagingTemplate;
@RequestMapping("/helloSocket")
public String index(){
return "/hello/index";
}
//注解为:接收客户端的value
@MessageMapping("/change-notice")
public void greeting(String value){
//向客户端发送value
this.simpMessagingTemplate.convertAndSend("/topic/notice", value);
}
}
以下与以上等同。
//接收
@MessageMapping("/change-notice")
//发送
@SendTo("/topic/notice")
public String greeting(String value) {
return value;
}
4.客户端接收与发送
发送
<script src="/js/sockjs-0.3.4.min.js"></script>
<script src="/js/stomp.min.js"></script>
<script>
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 = '';
}
// 开启socket连接
function connect() {
var socket = new SockJS('/socket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
});
}
// 断开socket连接
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
// 向‘/app/change-notice’服务端发送消息
function sendName() {
var value = document.getElementById('name').value;
stompClient.send("/app/change-notice", {}, value);
}
connect();
</script>
接收:
var noticeSocket = function () {
var s = new SockJS('/socket');
var stompClient = Stomp.over(s);
stompClient.connect({}, function () {
console.log('notice socket connected!');
//客户端接收
stompClient.subscribe('/topic/notice', function (data) {
$('.message span.content').html(data.body);
});
});
};