1.简单版
@RequestMapping("/socket")
@RestController
public class MsgController {
@Autowired
private MyWebSocketHandler myMessageHandler;
@RequestMapping("/send1")
public String sendMessageByUser(@RequestParam String contents) {
Map<String, WebSocketSession> users = myMessageHandler.getUserMap();
for(Map.Entry<String, WebSocketSession> map : users.entrySet()){
try {
myMessageHandler.handleMessage(map.getValue(), new TextMessage(contents));
} catch (Exception e) {
e.printStackTrace();
}
}
return "success";
}
}
@Component
public class MyWebSocketHandler implements WebSocketHandler {
public static final String USER_KEY = "socket_user";
private static final int size = 30;
private final Map<String, WebSocketSession> USER_MAP = new HashMap<>();
//连接成功
@Override
public void afterConnectionEstablished(WebSocketSession session) {
String user_key = getUser(session);
if(!ObjectUtils.isEmpty(user_key)){
USER_MAP.put(user_key, session);
}
}
//处理发送消息
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
String msg = message.toString();
String userId = this.getUser(session);
System.out.println("该"+userId+"用户发送的消息是:"+msg);
message = new TextMessage("服务端已经接收到消息,msg="+msg);
session.sendMessage(message);
}
//异常
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
WebSocketMessage<String> message = new TextMessage("异常信息:"+exception.getMessage());
session.sendMessage(message);
}
//关闭连接
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
if (session.isOpen()) {
session.close();
}
String userId = this.getUser(session);
if(!ObjectUtils.isEmpty(userId)){
USER_MAP.remove(userId);
System.out.println(userId +"用户已成功关闭会话");
}else{
System.out.println("关闭时,获取用户id为空");
}
}
@Override
public boolean supportsPartialMessages() {
return false;
}
private String getUser(WebSocketSession session) {
try {
String uname = session.getAttributes().get(USER_KEY).toString();
return uname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Map<String, WebSocketSession> getUserMap() {
return this.USER_MAP;
}
}
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private String path = "/socket";
@Autowired
private MyWebSocketHandler socketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(socketHandler, path).addInterceptors(new WebSocketInterceptor()).setAllowedOrigins("*");
}
}
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
if(request instanceof ServletServerHttpRequest){
HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
HttpSession session = httpServletRequest.getSession(true);
//获取参数
// String userId = serverHttpRequest.getParameter("userId");
attributes.put(MyWebSocketHandler.USER_KEY, session.getId());
return true;
}
return true;
}
}
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
|