WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
org.springframework.boot
spring-boot-starter-websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{clientId}")
@Slf4j
public class WebSocketServer {
/**
* 客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 客户端id
*/
private String clientId;
/**
* 用来存放每个客户端对应的MyWebSocket对象
*/
private static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet<>();
/**
* 用来存在线连接用户信息
*/
private static ConcurrentHashMap sessionPool = new ConcurrentHashMap();
/**
* 链接成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "clientId") String clientId) {
try {
this.session = session;
this.clientId = clientId;
webSockets.add(this);
sessionPool.put(clientId, session);
log.info("【websocket消息】有新的连接 clientId:{},总数为:{}", clientId, webSockets.size());
} catch (Exception e) {
log.info("【websocket消息】有新的连接构建失败 clientId:{},总数为:{},error:", clientId, webSockets.size(), e);
}
}
/**
* 链接关闭调用的方法
*/
@OnClose
public void onClose() {
try {
webSockets.remove(this);
sessionPool.remove(this.clientId);
log.info("【websocket消息】连接断开 clientId:{},总数为:{}", this.clientId, webSockets.size());
} catch (Exception e) {
log.info("【websocket消息】连接断开失败 clientId:{},总数为:{},error:", clientId, webSockets.size(), e);
}
}
/**
* 收到客户端消息后调用的方法
*/
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端消息:{}", message);
}
/**
* 发送错误时的处理
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("【websocket消息】发生错误,原因:", error);
}
/**
* 此为广播消息
*/
public void sendBroadcastMessage(String message) {
log.info("【websocket消息】广播消息:{}", message);
for (WebSocketServer webSocket : webSockets) {
try {
if (webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
log.error("【websocket消息】广播消息异常,消息:{},error:", message, e);
}
}
}
/**
* 此为单点消息
*/
public void sendSinglePointMessage(String targetId, String message) {
Session session = sessionPool.get(targetId);
if (session != null && session.isOpen()) {
try {
session.getAsyncRemote().sendText(message);
log.info("【websocket消息】单点消息,targetId:{},消息:{}", targetId, message);
} catch (Exception e) {
log.error("【websocket消息】单点消息异常,targetId:{},消息:{},error:", targetId, message, e);
}
}
}
}
Websocket客户端
客户端身份标识ID
客户端向服务器发送的内容
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket/{clientId}")
@Slf4j
public class WebSocketServer {
/**
* 客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 客户端id
*/
private String clientId;
/**
* 用来存放每个客户端对应的MyWebSocket对象
*/
private static CopyOnWriteArraySet webSockets = new CopyOnWriteArraySet<>();
/**
* 用来存在线连接用户信息
*/
private static ConcurrentHashMap sessionPool = new ConcurrentHashMap();
/**
* 链接成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "clientId") String clientId) {
try {
this.session = session;
this.clientId = clientId;
webSockets.add(this);
sessionPool.put(clientId, session);
log.info("【websocket消息】有新的连接 clientId:{},总数为:{}", clientId, webSockets.size());
} catch (Exception e) {
log.info("【websocket消息】有新的连接构建失败 clientId:{},总数为:{},error:", clientId, webSockets.size(), e);
}
}
/**
* 链接关闭调用的方法
*/
@OnClose
public void onClose() {
try {
webSockets.remove(this);
sessionPool.remove(this.clientId);
log.info("【websocket消息】连接断开 clientId:{},总数为:{}", this.clientId, webSockets.size());
} catch (Exception e) {
log.info("【websocket消息】连接断开失败 clientId:{},总数为:{},error:", clientId, webSockets.size(), e);
}
}
/**
* 收到客户端消息后调用的方法
*/
@OnMessage
public void onMessage(String message) {
log.info("【websocket消息】收到客户端消息:{}", message);
}
/**
* 发送错误时的处理
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("【websocket消息】发生错误,原因:", error);
}
/**
* 此为广播消息
*/
public void sendBroadcastMessage(String message) {
log.info("【websocket消息】广播消息:{}", message);
for (WebSocketServer webSocket : webSockets) {
try {
if (webSocket.session.isOpen()) {
webSocket.session.getAsyncRemote().sendText(message);
}
} catch (Exception e) {
log.error("【websocket消息】广播消息异常,消息:{},error:", message, e);
}
}
}
/**
* 此为单点消息
*/
public void sendSinglePointMessage(String targetId, String message) {
Session session = sessionPool.get(targetId);
if (session != null && session.isOpen()) {
try {
session.getAsyncRemote().sendText(message);
log.info("【websocket消息】单点消息,targetId:{},消息:{}", targetId, message);
} catch (Exception e) {
log.error("【websocket消息】单点消息异常,targetId:{},消息:{},error:", targetId, message, e);
}
}
}
}
发送广播消息:http://localhost:8081/api//websocket/sendBroadcastMessage?message=hello
发送点对点消息:http://localhost:8081/api//websocket/sendSinglePointMessage?message=hello&targetId=10