import com.future.websocket.client.PlatformHttpClient;
import com.future.websocket.client.SafetyHttpClient;
import com.future.websocket.config.RabbitMqConfig;
import com.future.websocket.mapper.OverViewMessageMapper;
import com.future.websocket.mapper.WorkstationMessageMapper;
import com.rabbitmq.client.Channel;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint(value = "/websocket/app/{workSiteNodeId}/{workNo}")
@Component
public class WebSocketServer2 {
private static PlatformHttpClient platformHttpClient;
@Autowired
public void setPlatformHttpClient(PlatformHttpClient platformHttpClient) {
//加载数据处理需要引用的Bean
WebSocketServer2.platformHttpClient = platformHttpClient;
}
private Logger logger = Logger.getLogger(WebSocketServer2.class);
/**
* 记录当前在线连接数
*//*
private static AtomicInteger onlineCount = new AtomicInteger(0);
*//**
* 连接建立成功调用的方法
*//*
@OnOpen
public void onOpen(Session session) {
onlineCount.incrementAndGet(); // 在线数加1
logger.info("有新连接加入:{}=" + session.getId());
logger.info("当前在线人数为:{}=" + onlineCount.get());
}
*//**
* 连接关闭调用的方法
*//*
@OnClose
public void onClose(Session session) {
onlineCount.decrementAndGet(); // 在线数减1
logger.info("有一连接关闭:{}" + session.getId());
logger.info("当前在线人数为:{}" + onlineCount.get());
}
*//**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*//*
@OnMessage
public void onMessage(String message, Session session) {
logger.info("服务端收到客户端[{}]" + session.getId());
logger.info("服务端收到客户端[{}]的消息:{}" + message);
this.sendMessage("Hello, " + message, session);
}
@OnError
public void onError(Session session, Throwable error) {
logger.error("发生错误");
error.printStackTrace();
}
*//**
* 服务端发送消息给客户端
*//*
private void sendMessage(String message, Session toSession) {
try {
logger.info("服务端给客户端[{}]" + toSession.getId());
logger.info("发送消息{}" + message);
toSession.getBasicRemote().sendText(message);
} catch (Exception e) {
logger.error("服务端发送消息给客户端失败:{}", e);
}
}*/
/**
* 存活的session集合(使用线程安全的map保存)
*/
private static Map<String, Session> livingSessions = new ConcurrentHashMap<>();
/**
* 建立连接的回调方法
*
* @param session 与客户端的WebSocket连接会话
* @param workNo 长连接来源,WebSocket支持路径参数
*/
@OnOpen
public void onOpen(Session session, @PathParam("workSiteNodeId") String workSiteNodeId, @PathParam("workNo") String workNo) {
String message = dealMessage(workSiteNodeId, workNo);
livingSessions.put(workNo, session);
sendMessageToAll(workNo, message);
}
@OnMessage
public void onMessage(String routeKey, Session session, @PathParam("workSiteNodeId") String workSiteNodeId,
@PathParam("workNo") String workNo) {
if (routeKey.equals("ping")) {
sendMessage(session, "pong");
} else {
String messageInfo = updateMessage(workSiteNodeId, workNo, routeKey);
sendMessageToAll(workNo, messageInfo);
}
}
@OnError
public void onError(Session session, Throwable error, @PathParam("routeKey") String routeKey) {
logger.info(routeKey + "发生错误");
logger.error(error.getStackTrace() + "");
}
@OnClose
public void onClose(Session session, @PathParam("dataSource") String dataSource) {
livingSessions.remove(session.getId());
logger.info(dataSource + " 关闭连接");
}
@RabbitHandler
@RabbitListener(queues = RabbitMqConfig.QUEUE_FIRE)
public void handler(String msg, Channel channel, Message message) {
//队列处理数据
}
/**
* 单独发送文本消息
*
* @param session
* @param message
*/
public void sendMessage(Session session, String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 单独发送文本消息
*
* @param session
* @param message
*/
public void sendMessageList(Session session, List<Map<String, Object>> message) {
try {
session.getBasicRemote().sendObject(message);
} catch (IOException | EncodeException e) {
e.printStackTrace();
}
}
/**
* 群发消息给有相关人
*
* @param message
*/
public void sendMessageToAll(String workNo, String message) {
livingSessions.forEach((workNum, session) -> {
//发给指定的接收用户
if (workNo.equals(workNum)) {
sendMessage(session, message);
}
});
}
/**
* 群发群消息
*
* @param message
*/
public void sendMessageListToAll(String message) {
livingSessions.forEach((sessionId, session) -> {
//发给指定的接收用户
// if (userId.equals(messageVo.getReceiveUserId())) {
sendMessage(session, message);
// }
});
}
public String updateMessage(String workSiteNodeId, String workNo, String routeKey) {
String message = dealMessage(workSiteNodeId, workNo);
return message;
}
public String dealMessage(String workSiteNodeId, String workNo) {
//数据处理
return "message";
}
}
SpringBoot+WebSocket实时推送前端数据
最新推荐文章于 2024-05-21 15:40:10 发布