Springboot webSocket应用

mac2024-03-09  30

package springboot_001.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * websocket配置文件 */ @Configuration public class WebsocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } package springboot_001.config; import lombok.extern.slf4j.Slf4j; 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.Set; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint("/websocket/{userAgentId}") @Component @Slf4j public class WebSocketUtil { public static ConcurrentHashMap<String, Session> linkCustomers = new ConcurrentHashMap<>(); //连接的客户端 /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session,@PathParam("userAgentId") String userAgentId) { log.info("新连接" + userAgentId, userAgentId); linkCustomers.put(userAgentId, session); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(@PathParam("userAgentId") String userAgentId) { log.info("断开连接", userAgentId); linkCustomers.remove("userAgentId"); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session, @PathParam("userAgentId") String userAgentId) { log.debug("收到" + userAgentId + "消息:" + message); } /** * 连接失败 * @param session * @param error */ @OnError public void onError(Session session, Throwable error, @PathParam("userAgentId") String userAgentId) { linkCustomers.remove(userAgentId); error.printStackTrace(); } /** * 实现服务器主动推送 */ public static void sendMessage(String message, Set<String> userAgentIds) throws IOException { for(String userAgentId : userAgentIds){ Session session = linkCustomers.get(userAgentId); if(session != null && session.isOpen()){ log.info(userAgentId + " 发送消息:" + message); session.getBasicRemote().sendText(message); } } } /** * 群发自定义消息 * */ public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException { } }

 

调用实例

if (StringUtils.isEmpty(message)) { if (params.get("SAFEGUARD_ID") != null) { //发送推送消息 Map<String, Object> mes = new HashMap<>(); mes.put("phoneStatus", "0"); mes.put("questionStatus", "1"); List<String> ids = new ArrayList<>(); Gson gson = new Gson(); Set<String> userIds = new HashSet<>(); // userIds.add("zwx815962"); // WebSocketUtil.sendMessage(gson.toJson(mes), userIds); WebSocketUtil.sendMessage(gson.toJson(mes), welinkService.getMesUserAgentId(params.get("SAFEGUARD_ID").toString()));

 

最新回复(0)