@Configuration
public class WebSocketConfig {
/**
-
注入ServerEndpointExporter,
-
这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 新建实现类:
@Component
@ServerEndpoint(“/ws/awdMatch/{userId}”)
public class AWDMatchWebSocket {
private Session session;
private static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet<>();
private static Map<Long, Session> sessionPool = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = “userId”) Long userId) {
this.session = session;
webSockets.add(this);
sessionPool.put(userId, session);
System.out.println(userId + " 已连接 \n【websocket消息】有新的连接,总数为:" + webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println(“【websocket消息】连接断开,总数为:” + webSockets.size());
}
@OnMessage
public void onMessage(String message) {
System.out.println(“【websocket消息】收到客户端消息:” + message);
}
/**
- 此为广播消息
*/
public void sendAllMessage(String message) {
for (AWDMatchWebSocket webSocket : webSockets) {
System.out.println(“【websocket消息】广播消息:” + message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
- 此为单点消息
*/
public void sendOneMessage(Long userId, String message) {
System.out.println(“【websocket消息】单点消息:” + message);
Session session = sessionPool.get(userId);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
- controller 新增调用类:
@Log
@Api(tags = “websocket 测试接口”)
@RestController
@RequestMapping(“ws”)
public class AwdMatchWSTestController {
@Autowired
private AWDMatchWebSocket webSocket;
@GetMapping(“/sendAllWebSocket”)
public String test() {
String text=“你们好!这是websocket群体发送!”;
webSocket.sendAllMessage(text);
return text;
}
@GetMapping(“/sendOneWebSocket/{userId}”)
public String sendOneWebSocket(@PathVariable Long userId) {
String text=userId+" 你好! 这是websocket单人发送!";
webSocket.sendOneMessage(userId,text);
return text;
}
}
- VUE部分: