全是贴图了:
多说无益!!!
开始:
实现一个某安的连接管理:
其中步骤1到7列的明明白白,而且一开始就提出了要有connectionManager,这已经是很职业的方式了,至少不是学生气:
这些肯定不够啊,要给我写代码来看看:
默认是python代码,风格良好。
不要用Python,我想用Java
从思路到代码,给安排的明明白白:
得寸进尺,要求用websocket !
进一步去问,ping/pong的实现机理:
这里直接用了中间的ping/pong ,而websocket这个关键词是从上文中带下来 的,这个回答,即说明了ping/pong的原理,也说清楚了实现方式:
这已经很是为难人了。。本拐不死心,继续追,关于稳定性:
问稳定性,已经是中级以上工程师的问题了,回答的处理异常和重连,中规中矩,但对于AI,知足吧!!!
再接着无赖,关于主备地址:
灾备情况,这个事儿其实已经超纲了,即使在工作中,这一层也不应该由应用层的人员来思考。
保持连接:
最终AI的代码如下:
public class WebSocketConnectionManager {private static WebSocketConnectionManager instance;private static String primaryAddress;private static String secondaryAddress;private static WebSocketClient client;private static WebSocketContainer container;private static Session session;public static WebSocketConnectionManager getInstance() {if (instance == null) {instance = new WebSocketConnectionManager();}return instance;}public void init(String primaryAddress, String secondaryAddress) {this.primaryAddress = primaryAddress;this.secondaryAddress = secondaryAddress;this.client = new WebSocketClient();this.container = ContainerProvider.getWebSocketContainer();}public boolean checkConnection() {return session != null && session.isOpen();}public void createConnection(String address) {try {URI uri = URI.create(address);client.start();session = container.connectToServer(this, uri);} catch (Exception e) {e.printStackTrace();}}public void changeAddress(String primaryAddress, String secondaryAddress) {if (session == null || !session.isOpen()) {createConnection(primaryAddress);} else if (session.getRequestURI().getHost().equals(primaryAddress)) {createConnection(secondaryAddress);} else {createConnection(primaryAddress);}}public void startHeartbeat(long interval, long timeout) {session.setMaxIdleTimeout(timeout);ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();executor.scheduleAtFixedRate(() -> {if (session.isOpen()) {session.getAsyncRemote().sendPing(null);}}, interval, interval, TimeUnit.MILLISECONDS);}@OnPongpublic void onPong(PongMessage message) {// 处理pong消息}public void reconnect(int retries, long interval, Runnable callback) {ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();executor.scheduleAtFixedRate(() -> {if (checkConnection()) {executor.shutdown();callback.run();}createConnection(primaryAddress);retries--;if (retries == 0) {executor.shutdown();callback.run();}}, 0, interval, TimeUnit.MILLISECONDS);}public void keepConnection(String primaryAddress, String secondaryAddress) {reconnect(3, 1000, () -> {if (checkConnection()) {return;}changeAddress(primaryAddress, secondaryAddress);});