package com.ld.igds.protocol.bhzn.verb.server; import com.ld.io.api.*; import com.ld.io.netty.NettyServer; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @Desc: 邦海智能纯粮情协议 * @author: Andy * @update-time: 2023/5/11 */ @Slf4j @Service public class BhznVerbServerEngine { public static final Integer PORT = 9310; @Autowired private BhznVerbMessageConsumer defaultMessageConsumer; @Autowired private BhznVerbSessionListener defaultSessionListener; // 心跳提供 private static HeartbeatProvider heartbeatProvider = new BhznVerbHeartbeatImpl(); private IoSessionQuery sessionQuery; public void start(Integer port) { IoServerOption ioServerOption = new IoServerOption(); if (null != port) { ioServerOption.setPort(port); } else { ioServerOption.setPort(PORT); } //确认结尾标志 ioServerOption.setDelimiter(BhznVerbServerUtils.MSG_END.getBytes()); // 配置系统心跳间隔 ioServerOption.setReaderIdleTime(5 * 60); NettyServer ioServer = new NettyServer(ioServerOption, defaultMessageConsumer, defaultSessionListener, heartbeatProvider); ioServer.startup(); sessionQuery = ioServer.getSessionQuery(); log.info("* "); log.info("* ========================"); log.info("* "); log.info("* [VERB-SERVER:BHZN_VERB,PORT={}]", PORT); log.info("* "); log.info("* ========================"); log.info("* "); System.out.println("* ========================"); System.out.println("* "); System.out.println("* [VERB-SERVER:BHZN_VERB,PORT={}]" + port); System.out.println("* "); System.out.println("* ========================"); } public IoSessionQuery getSessionQuery() { return sessionQuery; } /** * 发送信息 * * @param ip * @param port * @param msg * @return */ public InvokeResult push(String ip, int port, byte[] msg) { IoSessionQuery sessionFactory = getSessionQuery(); List sessions = sessionFactory.getAllSession(); IoSession session = null; for (IoSession ioSession : sessions) { if (BhznVerbServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) { session = ioSession; break; } } if (null == session) { return InvokeResult.CHANNEL_CLOSED; } return session.invoke(msg); } // public InvokeResult push(String ip, int port, String hexStr) { // // byte[] msg = BytesUtil.hexStrToBytes(hexStr); // // IoSessionQuery sessionFactory = getSessionQuery(); // List sessions = sessionFactory.getAllSession(); // IoSession session = null; // for (IoSession ioSession : sessions) { // if (BhznGrainV1ServerUtils.getServerKey(ip, port).equals(ioSession.getBusinessKey())) { // session = ioSession; // break; // } // } // // if (null == session) { // return InvokeResult.CHANNEL_CLOSED; // } // return session.invoke(msg); // } }