Spring + WebSocket的官方文档
测试效果WebSocket是一种双向通信协议。在建立连接后,WebSocket服务器端和客户端都能主动向对方发送或接收数据。
发送请求,触发WebSocket发消息到客户端
客户端接收到服务端发过来的消息
pom.xml加入依赖
org.springframework.boot spring-boot-starter-websocket
添加配置类
@Configuration
@EnableWebSocketMessageBroker //注解开启STOMP协议来传输基于代理的消息
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/endpoint")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//基于内存的STOMP消息代理
config.enableSimpleBroker("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
//单播时,默认前缀为/user,现修改为/queue
config.setUserDestinationPrefix("/queue");
}
}
编写业务代码
@RestController
@Api(value = "WebSocket发送消息", tags = {"WebSocket控制器"})
public class SubController {
@Autowired
private WebSocketService webSocketService;
@MessageMapping("/queue/check")
public void check() {
InMessage im = new InMessage<>();
im.setContent("topicCheck");
im.setTo("27");
im.setMsgType(200);
webSocketService.queue(im);
}
@PostMapping("/queue")
@ApiOperation("单播")
public void queue() {
InMessage im = new InMessage<>();
im.setContent("queue");
im.setTo("27");
im.setMsgType(200);
webSocketService.queue(im);
}
@PostMapping("/subscribe")
@ApiOperation("广播")
public void subscribe() {
InMessage im = new InMessage<>();
im.setContent("subscribe");
im.setTo("27");
im.setMsgType(200);
webSocketService.subscribe(im);
}
@PostMapping("/sendMessage")
@ApiOperation("单播或广播,根据sendUrl判断")
public void sendMessage(@RequestBody ContentMessage message) {
webSocketService.sendMessage(message);
}
}
js订阅代码
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
//后端放开的端点
var socket = new SockJS('http://localhost:8096/endpoint');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
//单播
stompClient.subscribe('/queue/27/message', function (greeting) {
showGreeting(greeting.body);
});
//广播
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
//需要添加服务端配置类中设置的/app前缀
stompClient.send("/app/queue/check", {}, $("#name").val());
}
function showGreeting(message) {
$("#greetings").append("" + message + " ");
}
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
服务端代码地址
客户端代码示例


