feat: websocket basic frame built
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package xin.merlin.myplayerbackend.utils.websocket;
|
||||
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class WebSocketSessionManager {
|
||||
|
||||
private static final Map<Integer, WebSocketSession> websocketSessions = new ConcurrentHashMap<>();
|
||||
|
||||
public void addSession(Integer id, WebSocketSession session) {websocketSessions.put(id, session);}
|
||||
|
||||
public WebSocketSession getSession(Integer id) {return websocketSessions.get(id);}
|
||||
|
||||
public void removeSession(Integer id) {websocketSessions.remove(id);}
|
||||
|
||||
public Map<Integer, WebSocketSession> getSessions() {return websocketSessions;}
|
||||
|
||||
public void sendToUser(Integer userId, String message) throws IOException {
|
||||
WebSocketSession session = websocketSessions.get(userId);
|
||||
if (session != null && session.isOpen()) {
|
||||
session.sendMessage(new TextMessage(message));
|
||||
}
|
||||
}
|
||||
|
||||
public void broadcast(String message) throws IOException {
|
||||
for (WebSocketSession session : websocketSessions.values()) {
|
||||
if (session.isOpen()) {
|
||||
session.sendMessage(new TextMessage(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user