依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
websocket服务端点
@ServerEndpoint("/ws/test/{username}")
@Component
public class TestEndpoint {
static final Logger loggger = LoggerFactory.getLogger(TestEndpoint.class);
private static int onlineCount = 0;
private static ConcurrentHashMap<String, TestEndpoint> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String username = "";
public static void sendInfo(String message, String username) {
loggger.info("发送消息到:" + username + ",报文:" + message);
if (StringUtils.isNotBlank(username) && webSocketMap.containsKey(username)) {
try {
webSocketMap.get(username).sendMessage(message);
} catch (Exception e) {
loggger.error(e.getMessage(), e);
}
} else {
loggger.error("用户" + username + ",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
TestEndpoint.onlineCount++;
}
public static synchronized void subOnlineCount() {
TestEndpoint.onlineCount--;
}
@OnOpen
public void onOpen(Session session, @PathParam("username") String username) {
this.session = session;
this.username = username;
if (webSocketMap.containsKey(username)) {
webSocketMap.remove(username);
webSocketMap.put(username, this);
} else {
webSocketMap.put(username, this);
addOnlineCount();
}
loggger.info("用户连接:" + username + ",当前在线人数为:" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
loggger.error("用户:" + username + ",网络异常!!!!!!");
}
}
@OnClose
public void onClose() {
if (webSocketMap.containsKey(username)) {
webSocketMap.remove(username);
subOnlineCount();
}
loggger.info("用户退出:" + username + ",当前在线人数为:" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
loggger.info("用户消息:" + username + ",报文:" + message);
}
@OnError
public void onError(Session session, Throwable error) {
loggger.error("用户错误:" + this.username + ",原因:" + error.getMessage());
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
}
客户端
var webSocket = null;
if ('WebSocket' in window) {
webSocket = new WebSocket('ws://serverhost/ws/test/username');
webSocket.onmessage = function (event) {
}
webSocket.onclose = function () {
}
webSocket.onerror = function () {
}
webSocket.onopen = function () {
var message = "msgfromclient";
webSocket.send(message);
}
} else {
alert('Not support websocket')
}