1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.web.socket.*; import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import java.io.IOException; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap;
public class WebSocketHandler extends AbstractWebSocketHandler {
private static Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>(); private static Map<String, String> userMap = new ConcurrentHashMap<>();
@Override public void afterConnectionEstablished(WebSocketSession session) {
userMap.put("user", session.getId()); sessionMap.put(session.getId(), session); }
@Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { JSONObject jsonObject = JSONObject.parseObject(message.getPayload().toString()); String username = jsonObject.getString("username"); String password = jsonObject.getString("password"); sendMessage(username, "hello user"); sendMessage(username, "data content is json data"+password+message.getPayload().toString()); }
@Override public void handleTransportError(WebSocketSession session, Throwable exception) { sessionMap.remove(session.getId()); }
@Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { sessionMap.remove(session.getId()); }
@Override public boolean supportsPartialMessages() { return false; }
public void sendMessage(String user, String message) throws IOException { String sessionId = userMap.get("user"); if (StringUtils.isEmpty(sessionId)) { return; } WebSocketSession session = sessionMap.get(sessionId); if (session == null) { return; } session.sendMessage(new TextMessage(message)); } }
|