SocketService.java 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package com.ruoyi.sim.service.impl;
  2. import com.ruoyi.common.core.domain.AjaxResult;
  3. import com.ruoyi.sim.config.SimConfig;
  4. import com.ruoyi.sim.config.SimDebugConfig;
  5. import com.ruoyi.sim.domain.Seat;
  6. import com.ruoyi.sim.domain.vo.SimSocketParamVo;
  7. import com.ruoyi.sim.domain.vo.SocketWrapCacheVo;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.security.core.parameters.P;
  12. import org.springframework.stereotype.Service;
  13. import java.io.IOException;
  14. import java.net.InetAddress;
  15. import java.net.Socket;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.concurrent.atomic.AtomicInteger;
  19. import static com.ruoyi.sim.constant.CommConst.SOCKET_TIME_OUT;
  20. /**
  21. * 1.所有Socket常开。
  22. * todo: connectedTimeMillis 时间。
  23. * <p>
  24. * 创建Socket重试,用failed开始方法去操作。
  25. */
  26. @Service
  27. public class SocketService {
  28. private static final Logger l = LoggerFactory.getLogger(SocketService.class);
  29. /**
  30. * 硬件孙总北京办公室,测试远程地址
  31. * <p>
  32. * 孙总办公室域名
  33. * nas.yichiot.com
  34. */
  35. public static final String IP_TEST = "221.218.215.73";
  36. public static final int PORT_TEST = 8899;
  37. private static final int LOCAL_PORT = 9000;
  38. private static final int INIT_SIZE = 32;
  39. /**
  40. * 6 hours
  41. * 1000L * 60 * 60 * 6
  42. * 1000L * 60 * 5
  43. */
  44. private static final long TIMEOUT_LIMIT = 1000L * 60 * 60 * 6;
  45. public static final int SOCKET_CONNECT_RETRY_COUNT_LIMIT = 4;
  46. /**
  47. * key: ip:port
  48. * value:
  49. */
  50. private static HashMap<String, SocketWrapCacheVo> cachedMap = new HashMap<>(INIT_SIZE);
  51. /**
  52. * 每个Socket都有。
  53. * 重试次数。
  54. * default 0.
  55. */
  56. private static HashMap<String, AtomicInteger> failedMap = new HashMap<>(INIT_SIZE);
  57. @Autowired
  58. private SimConfig config;
  59. @Autowired
  60. private SeatService seatService;
  61. /**
  62. * @param sspv
  63. * @return true:socket ok!
  64. */
  65. public boolean isOk(final SimSocketParamVo sspv) {
  66. final String key = sspv.toKey();
  67. if (cachedMap.containsKey(key) && cachedMap.get(key) != null) {
  68. Socket s = cachedMap.get(key).getSocket();
  69. if (s != null) {
  70. return (s.isConnected() && s.isBound() && !s.isClosed());
  71. }
  72. }
  73. return false;
  74. }
  75. public boolean isNotOk(final SimSocketParamVo sspv) {
  76. return !isOk(sspv);
  77. }
  78. /**
  79. * 暂时不考虑超时周期。
  80. * todo:
  81. *
  82. * @param ssv
  83. * @return
  84. */
  85. public boolean isTimeout(SimSocketParamVo ssv) {
  86. if (cachedMap.containsKey(ssv.toKey())) {
  87. Long cached = cachedMap.get(ssv.toKey()).getOkTimeMillis();
  88. if (cached == null || cached == 0L) {
  89. return true;
  90. }
  91. return System.currentTimeMillis() - cached <= TIMEOUT_LIMIT;
  92. }
  93. return true;
  94. }
  95. /**
  96. * @param sspv
  97. * @param force 是否强制使用新连接的Socket
  98. * @return
  99. */
  100. public AjaxResult openOne(final SimSocketParamVo sspv, final boolean force) {
  101. // check.
  102. if (!config.isCommGlobal()) {
  103. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  104. return AjaxResult.error("模拟器通信被禁用!");
  105. }
  106. //
  107. try {
  108. if (isNotOk(sspv) || force) {
  109. final String key = sspv.toKey();
  110. l.info("openSocket cachedSocket is not ok!try new socket ip = {}:{}!forceNew = {}", sspv.getIp(), sspv.getPort(), force);
  111. closeOne(sspv, false);
  112. // 不指定本地端口实现。
  113. Socket s = new Socket(sspv.getIp(), sspv.getPort());
  114. // todo: LOCAL_PORT
  115. // Socket s = new Socket(sspv.getIp(), sspv.getPort(), InetAddress.getLocalHost(), SimDebugConfig.TCP_LOCAL_PORT);
  116. s.setSoTimeout(SOCKET_TIME_OUT);
  117. SocketWrapCacheVo value = new SocketWrapCacheVo(sspv.getIp(), sspv.getPort(), s, System.currentTimeMillis());
  118. // 新建Socket需要挂起 2s后再发指令。
  119. value.setPreviousSendSleep(2000L);
  120. cachedMap.put(key, value);
  121. // socket failed count reset.
  122. failedReset0(sspv);
  123. } else {
  124. l.info("openSocket cachedSocket cache ok!cached socket ip = {}:{}!forceNew = {}", sspv.getIp(), sspv.getPort(), force);
  125. }
  126. Seat seat = seatService.uniqueByRs485IpAndPort(sspv.getIp(), sspv.getPort());
  127. seat.setSeatRs485SocketState(Seat.SocketState.ONLINE);
  128. seatService.updateSeat(seat);
  129. return AjaxResult.success("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],创建成功!");
  130. } catch (IOException e) {
  131. l.error("IOException = {}", sspv);
  132. if (failedIsReachedMax(sspv, SOCKET_CONNECT_RETRY_COUNT_LIMIT)) {
  133. return AjaxResult.error("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],重试[" + failedGet(sspv) + "]次,创建失败!");
  134. } else {
  135. failedPlus1(sspv);
  136. AjaxResult ar = openOne(sspv, force);
  137. if (ar.isSuccess()) {
  138. return ar;
  139. } else {
  140. return AjaxResult.error("Socket[" + sspv.getIp() + ":" + sspv.getPort() + "],进行重试,创建失败!");
  141. }
  142. }
  143. }
  144. }
  145. public AjaxResult tryOpenOne(final SimSocketParamVo sspv) {
  146. if (!config.isCommGlobal()) {
  147. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  148. return AjaxResult.error("模拟器通信被禁用!");
  149. }
  150. return openOne(sspv, false);
  151. }
  152. /**
  153. * todo:部分返回Aj结果。
  154. *
  155. * @return
  156. */
  157. public AjaxResult tryOpenAll() {
  158. if (!config.isCommGlobal()) {
  159. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  160. return AjaxResult.error("模拟器通信被禁用!");
  161. }
  162. List<Seat> allSeat = seatService.listAllEnable();
  163. for (Seat s : allSeat) {
  164. AjaxResult ar = openOne(s.toSimSocketParamVo(), false);
  165. l.debug("AjaxResult = {}", ar);
  166. }
  167. return AjaxResult.success("所有Socket,创建成功!");
  168. }
  169. public AjaxResult closeOne(final SimSocketParamVo sspv, boolean failedReset) {
  170. if (!config.isCommGlobal()) {
  171. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  172. return AjaxResult.error("模拟器通信被禁用!");
  173. }
  174. final String key = sspv.toKey();
  175. try {
  176. if (cachedMap.containsKey(key)) {
  177. Socket s = cachedMap.get(key).getSocket();
  178. s.getInputStream().close();
  179. s.getOutputStream().close();
  180. s.close();
  181. }
  182. } catch (IOException e) {
  183. e.printStackTrace();
  184. } finally {
  185. if (failedReset) {
  186. // failed count reset.
  187. failedReset0(sspv);
  188. }
  189. cachedMap.remove(key);
  190. return AjaxResult.success("关闭Socket成功!");
  191. }
  192. }
  193. public AjaxResult closeAll() {
  194. if (!config.isCommGlobal()) {
  195. l.warn("isCommGlobal == {} [模拟器通信被禁用!]", config.isCommGlobal());
  196. return AjaxResult.error("模拟器通信被禁用!");
  197. }
  198. final String msgOk = "关闭所有Socket成功!";
  199. List<Seat> allSeat = seatService.listAllEnable();
  200. for (Seat s : allSeat) {
  201. closeOne(new SimSocketParamVo(s.getSeatRs485Ip(), s.getSeatRs485Port()), true);
  202. }
  203. return AjaxResult.success(msgOk);
  204. }
  205. /**
  206. * @param seat
  207. * @return todo:null
  208. */
  209. public SocketWrapCacheVo get(final Seat seat) {
  210. if (seat == null) {
  211. throw new IllegalArgumentException("seat为空。");
  212. }
  213. return get(new SimSocketParamVo(seat.getSeatRs485Ip(), seat.getSeatRs485Port()));
  214. }
  215. /**
  216. * @param sspv
  217. * @return
  218. */
  219. public SocketWrapCacheVo get(final SimSocketParamVo sspv) {
  220. if (isNotOk(sspv)) {
  221. AjaxResult ar = openOne(sspv, true);
  222. if (ar.isError()) {
  223. // todo: isError
  224. }
  225. }
  226. return cachedMap.get(sspv.toKey());
  227. }
  228. /**
  229. * 初始化。todo:
  230. */
  231. public void clear(final SimSocketParamVo sspv) {
  232. }
  233. private static final int SOCKET_FAILED_COUNT_0 = 0;
  234. private static final int SOCKET_FAILED_COUNT_ADD_1 = 1;
  235. /**
  236. * @param sspv
  237. * @param limit include limit
  238. * @return
  239. */
  240. public boolean failedIsReachedMax(final SimSocketParamVo sspv, final int limit) {
  241. final String key = sspv.toKey();
  242. return (failedMap.containsKey(key) && failedMap.get(key).get() >= limit);
  243. }
  244. public int failedPlus1(final SimSocketParamVo sspv) {
  245. final String key = sspv.toKey();
  246. if (!failedMap.containsKey(key)) {
  247. failedMap.put(key, new AtomicInteger(SOCKET_FAILED_COUNT_ADD_1));
  248. } else {
  249. failedMap.get(key).addAndGet(SOCKET_FAILED_COUNT_ADD_1);
  250. }
  251. return failedMap.get(key).get();
  252. }
  253. public int failedGet(final SimSocketParamVo sspv) {
  254. final String key = sspv.toKey();
  255. if (failedMap.containsKey(key)) {
  256. return failedMap.get(key).get();
  257. } else {
  258. return SOCKET_FAILED_COUNT_0;
  259. }
  260. }
  261. public void failedReset0(final SimSocketParamVo sspv) {
  262. final String key = sspv.toKey();
  263. if (failedMap.containsKey(key)) {
  264. failedMap.get(key).set(SOCKET_FAILED_COUNT_0);
  265. } else {
  266. l.debug("not containsKey SimSocketParamVo sspv:" + sspv);
  267. }
  268. }
  269. }