基本配置
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
```java
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint(value = "/ttlMallSocket/{userName}")
public class WebSocketServer {
private static int onlineCount = 0;
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
private Session session;
private static Map<String, Session> sessionsMap = new HashMap<>();
@OnOpen
public void onOpen(Session session,@PathParam(value = "userName") String userName) {
System.out.println("连接成功;");
this.session = session;
webSocketSet.add(this);
addOnlineCount();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
sessionsMap.put(uuid, this.session);
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendInfo(uuid,"欢迎" + userName + "加入连接!");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInfo(String uuid, String message) {
Session session = sessionsMap.get(uuid);
try {
sendMessage(session, message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendMessage(Session session, String message) throws IOException {
if (session != null) {
session.getBasicRemote().sendText(message);
}
}
@OnClose
public void onClose(String uuid) {
webSocketSet.remove(this);
sessionsMap.remove("uuid");
subOnlineCount();
System.out.println( "断开webSocket连接!当前人数为" + getOnlineCount());
}
@OnMessage
public void onMessage(String message) throws IOException {
try {
for (Session session : sessionsMap.values()) {
sendMessage(session, message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("发生错误");
throwable.printStackTrace();
}
private static synchronized int getOnlineCount() {
return onlineCount;
}
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}