一、WebSocket简介
WebSocket是一种在 TCP 连接上进行全双工通信的协议,建立客户端和服务器之间的通信渠道。浏览器和服务器仅需一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
二、实现步骤
1、SpringBoot 整合 Websocket
<!-- 引入websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、WebSocket 服务器
@Slf4j
@Component
@ServerEndpoint("/websocket/{userName}")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam(value="userName")String userName) {
this.session = session;
webSockets.add(this);
sessionPool.put(userName, session);
System.out.println("【websocket消息】有新用户" + userName +"接入,当前在线总数为:"+webSockets.size());
}
@OnClose
public void onClose() {
try {
webSockets.remove(this);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnMessage
public void onMessage(String message,@PathParam(value="userName")String userName) {
System.out.println("【websocket消息】收到" + userName + "消息:" + message);
}
/**
* 集体通知
* @param message
*/
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("群体通知:"+message);
try {
webSocket.session.getAsyncRemote().sendText("群体通知:"+message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 单用户通知
* @param userName
* @param message
*/
public void sendOneMessage(String userName, String message) {
log.info("站内消息给{}发送了{}",userName,message);
Session session = sessionPool.get(userName);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3、客户端可以使用postman发起webSocket请求