Spring boot Stomp WebSocket

Spring boot Stomp WebSocket

依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置WebSocketConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//设置websocket订阅前缀
config.enableSimpleBroker("/topic");
//设置websocket访问前缀
config.setApplicationDestinationPrefixes("/app");
}

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket")
//使用拦截器认证用户
.addInterceptors(new HandshakeInterceptor() {

@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
//在这里获取token认证
return true;
}

@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Exception exception) {
}
})
.withSockJS();
}

}

消息控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Controller
public class GreetingController {

@Autowired
private SimpMessagingTemplate messagingTemplate;

//通知消息
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
return new Greeting("Hello, " + message.getName() + "!");
}

//指定用户消息
@MessageMapping("/toUser")
public void toUser(ToUserMessage message) throws Exception {
System.out.println(message);
messagingTemplate.convertAndSend("/topic/" + message.getUserId(), message);
}

}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//依赖SockJS-client和STOMP.js
var stompClient = null;
//连接可加入认证参数,方便服务端认证
var socket = new SockJS('/gs-guide-websocket?userId=' + userId);
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
//订阅/topic/greetings
stompClient.subscribe('/topic/greetings', function (greeting) {
console.log(greeting.body);
});
//订阅/topic/{userId}
stompClient.subscribe('/topic/' + userId, function (data) {
console.log(data.body);
});
});
//发送消息
stompClient.send("/app/hello", {}, JSON.stringify({'name': 'zhang'}));
//发送到指定用户
stompClient.send("/app/toUser", {}, JSON.stringify({'userId': userId, 'message': 'hello'}));