1. Introduction to WebSocket
WebSocket is a protocol for full-duplex communication over a TCP connection, establishing a communication channel between the client and the server. The browser and server only need one handshake, and a persistent connection can be created directly between the two for bidirectional data transmission.
2. Implementation steps
1. SpringBoot integrates Websocket
<!-- 引入websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. WebSocket server
@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. The client can use postman to initiate a webSocket request.