参考文档
https://blog.csdn.net/qq_15807785/article/details/83547978
https://blog.csdn.net/u014534808/article/details/108906050
接口测试地址:
http://www.jsons.cn/websocket/
websocket特点
可以向客户端发送消息
特别注意:websocket接口类不能被自定义aop拦截,可能会出现问题
示例
添加依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
@Componentpublic class WebSocketConfig {/*** ServerEndpointExporter作用* 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint*/@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}@Slf4j@Component@ServerEndpoint("/ws/{name}")public class WebSocketController {/*** 与某个客户端的连接对话,需要通过它来给客户端发送消息*/private Session session;/*** 标识当前连接客户端的用户名*/private String name;private static ConcurrentHashMap<String, WebSocketController> websocketSet = new ConcurrentHashMap<>();@OnOpenpublic void OnOpen(Session session, @PathParam("name") String name) {this.session = session;this.name = name;//name是用来表示唯一客户端,如果需要指定发送,需要指定发送通过name来区分websocketSet.put(name, this);log.info("[WebSocket]连接成功,当前连接人数为={}", websocketSet.size());}@OnClosepublic void OnClose() {websocketSet.remove(this.name);log.info("[WebSocket]退出成功,当前连接人数为={}", websocketSet.size());}@OnErrorpublic void onError(Throwable e) {// ......}@OnMessagepublic void OnMessage(String message) {log.info("[WebSocket]收到消息={}", message);groupSending("客户端的消息我已经收到了");System.out.println("receive " + message);}public void groupSending(String message) {for (String name : websocketSet.keySet()) {try {websocketSet.get(name).session.getBasicRemote().sendText(message);} catch (IOException e) {e.printStackTrace();}}}}
