_TcpComClient.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. using System;
  2. using System.Text;
  3. using System.Collections;
  4. using System.Net.Sockets;
  5. using System.Net;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. using System.Net.NetworkInformation;
  9. //using System.Management.Instrumentation;
  10. //using System.Management;
  11. namespace FPER
  12. {
  13. // TCP 공통 루틴은 여기에서 구현한다
  14. // 출입통제 전용 소프트웨어간 통신을 위해 구현된다 (1개의 PC에 포트별로 하나의 프로그램이 연결된다)
  15. // 소켓의 세션을 유지하여 운영된다 (클라이언트용)
  16. public class _TcpComClient // cyim 2015.8.4 수신반을 위한 static 클래스 정리
  17. {
  18. // cyim 2015.8.4 수신반을 위한 static 클래스 정리
  19. MDIParent mdi = null;
  20. // 접속 응답 대기 시간 MicroSecond
  21. public const int WaitPollTime = 10000; // 사용안함
  22. // 수신 버퍼 크기
  23. public const int RxBufSize = 64; // 소방은 작다 (1개당 4byte 가 필요하므로 16 * 4) // cyim 2014.8.11 : 소방 수신 버퍼 사이즈 변경
  24. // 소켓 접속 혹은 종료 알림 이벤트
  25. public delegate void SocketConnect_Inform_Message_Handler(object data, bool Connect);
  26. public event SocketConnect_Inform_Message_Handler SocketConnect_Inform_Event;
  27. // TxConnect 클라이언트 소켓을 관리하기 위한 해쉬테이블 (클라이언트용)
  28. public Hashtable TxConnect_Socket = new Hashtable();
  29. // TxConnect 클라이언트 소켓세션이 종료되었는지 관리 (클라이언트용 : TxConnect_Socket 동일하게 생성 및 삭제가 됨)
  30. public Hashtable TxConnect_KeepTimer = new Hashtable();
  31. // 생성자
  32. public _TcpComClient(MDIParent mdiparent)
  33. {
  34. mdi = mdiparent;
  35. }
  36. // 소멸자
  37. ~_TcpComClient()
  38. {
  39. }
  40. // 클라이언트로 동작시 Connect 소켓 생성
  41. public void Create_TxConnect_Socket(string Key, Socket RxSocket, System.Threading.Timer Timer)
  42. {
  43. if (TxConnect_Socket.Contains(Key) == true)
  44. {
  45. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + Key + " Socket " + "이미 키가 중복입니다");
  46. }
  47. else
  48. {
  49. // 해쉬에 추가
  50. //TxConnect_KeepTimer.Add(Key, Timer);
  51. TxConnect_Socket.Add(Key, RxSocket);
  52. }
  53. }
  54. // TxConnect_Socket 소켓 삭제
  55. public void Delete_TxConnect_Socket(string Key)
  56. {
  57. // 모두 삭제
  58. if (Key == null)
  59. {
  60. foreach (DictionaryEntry d in TxConnect_Socket)
  61. ((Socket)d.Value).Dispose();
  62. //foreach (DictionaryEntry d in TxConnect_KeepTimer)
  63. // ((System.Threading.Timer)d.Value).Dispose();
  64. //TxConnect_KeepTimer.Clear();
  65. TxConnect_Socket.Clear();
  66. }
  67. // 부분 삭제
  68. else
  69. {
  70. if (TxConnect_Socket.Contains(Key) == true)
  71. {
  72. // 소켓 삭제
  73. if (((Socket)TxConnect_Socket[Key]) != null)
  74. ((Socket)TxConnect_Socket[Key]).Close();
  75. // 타이머도 삭제
  76. //if (((System.Threading.Timer)TxConnect_KeepTimer[Key]) != null)
  77. // ((System.Threading.Timer)TxConnect_KeepTimer[Key]).Dispose();
  78. //// 해쉬에서 삭제
  79. //TxConnect_KeepTimer.Remove(Key);
  80. TxConnect_Socket.Remove(Key);
  81. }
  82. }
  83. }
  84. // 수신 큐
  85. public Queue RxQueue = new Queue();
  86. // 발신 큐
  87. public Queue TxQueue = new Queue();
  88. // Critical Section
  89. public Object CS_TxQueue = new Object();
  90. public Object CS_RxQueue = new Object();
  91. // 종단 포맷 (소켓처리용)
  92. public class EndPointFormat
  93. {
  94. public string IP = null;
  95. public string Port = null;
  96. public byte[] Msg = null;
  97. }
  98. // 전송 포맷 (메세지처리용)
  99. public class SendFormat
  100. {
  101. public string IP = null;
  102. public string Port = null;
  103. public string Msg = null;
  104. }
  105. // 카드홀더 전송 포맷
  106. public class SendFormat_CardHolder
  107. {
  108. public string IP = null;
  109. public string Port = null;
  110. public string Msg = null;
  111. public string Protocol = null;
  112. public string UID= null;
  113. }
  114. //
  115. // Queue
  116. //
  117. public void RxQueue_ADD(EndPointFormat Data)
  118. {
  119. lock (CS_RxQueue)
  120. {
  121. RxQueue.Enqueue(Data);
  122. }
  123. }
  124. public void TxQueue_ADD(SendFormat Data)
  125. {
  126. lock (CS_TxQueue)
  127. {
  128. TxQueue.Enqueue(Data);
  129. }
  130. }
  131. //
  132. // Socket Status 알아내기
  133. //
  134. //public bool Socket_Status(Socket socket)
  135. //{
  136. //try
  137. //{
  138. //if (socket == null) return false;
  139. //bool part1 = socket.Poll(1000, SelectMode.SelectRead);
  140. //bool part2 = socket.Available == 0;
  141. //if (part1 & part2)
  142. // return false;
  143. //else
  144. // return true;
  145. //}
  146. //catch (Exception ex)
  147. //{
  148. //Util.UErrorMessage(ex, 0, 0);
  149. //return false;
  150. //}
  151. //}
  152. //
  153. // RX
  154. //
  155. // 서버에 접속하여 메세지를 수신할수 있도록 대기
  156. public bool Socket_Connect(string DestIP, string DestPort)
  157. {
  158. // Connect 된 소켓은 아이피와 포트를 키로 두고 처리한다
  159. string TxConnect_Socket_Key = DestIP + ":" + DestPort;
  160. try
  161. {
  162. // 연결된 소켓이 없다면 생성
  163. if (TxConnect_Socket.ContainsKey(TxConnect_Socket_Key) == false)
  164. {
  165. // 타겟이 접속이 가능한지 체크해서 소켓을 생성, 안에서 이미 소켓을 해쉬에 생성해버린다
  166. Socket TxSocket = Send_Check(DestIP, DestPort, WaitPollTime);
  167. if (TxSocket != null)
  168. {
  169. // 포맷 생성
  170. EndPointFormat RxQueFormat = new EndPointFormat();
  171. // IP
  172. RxQueFormat.IP = DestIP;
  173. // PORT
  174. RxQueFormat.Port = DestPort;
  175. // 상대방의 메시지 수신을 기다리는 스레드를 생성한다
  176. mdi.Thread.Abort(TxConnect_Socket_Key);
  177. mdi.Thread.Create(TxConnect_Socket_Key, Socket_Receive_byThread, RxQueFormat);
  178. //_Data.Exception_Log_Display = true;
  179. return true;
  180. }
  181. else
  182. return false;
  183. }
  184. else
  185. {
  186. // 있더라도 접속이 가능한지 체크
  187. //if (Socket_Status(((Socket)TxConnect_Socket[TxConnect_Socket_Key])) == false)
  188. if (Ping_SyncCheck(DestIP) == false)
  189. {
  190. // 소켓 해제
  191. Socket_Close(TxConnect_Socket_Key);
  192. return false;
  193. }
  194. else
  195. {
  196. return true;
  197. }
  198. }
  199. }
  200. catch (Exception ex)
  201. {
  202. Util.UErrorMessage(ex, 0, 0);
  203. // 특별처리 : 접속이 된상태에서 오류가 발생하면 출력
  204. //if (_Data.Exception_Log_Display == true)
  205. //{
  206. // // 1회만 로그 출력
  207. // _Data.Exception_Log_Display = false;
  208. // LOG
  209. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + ex.ToString());
  210. //}
  211. return false;
  212. }
  213. }
  214. // RX : 메세지 수신 스레드 (접속 요청이 들어오면 메세지를 받는 스레드)
  215. public void Socket_Receive_byThread(object QueFormat)
  216. {
  217. EndPointFormat Dest = (EndPointFormat)QueFormat;
  218. string TxConnect_Socket_Key = Dest.IP + ":" + Dest.Port;
  219. //while (Socket_Status((Socket)TxConnect_Socket[TxConnect_Socket_Key]) == true)
  220. while (true)
  221. {
  222. try
  223. {
  224. // 버퍼 생성
  225. Byte[] ReceiveByte = new Byte[RxBufSize];
  226. // 블럭킹
  227. ((Socket)TxConnect_Socket[TxConnect_Socket_Key]).Blocking = true;
  228. // 이는 메세지를 받기 위한 전용 소켓이다..
  229. int RxDataCnt = ((Socket)TxConnect_Socket[TxConnect_Socket_Key]).Receive(ReceiveByte, ReceiveByte.Length, SocketFlags.None);
  230. // 수신 버퍼 갯수
  231. if (RxDataCnt > 0)
  232. {
  233. // 수신용 소켓 정보
  234. EndPointFormat RxQueFormat = new EndPointFormat();
  235. // IP
  236. RxQueFormat.IP = Dest.IP;
  237. // Port
  238. RxQueFormat.Port = Dest.Port;
  239. // Message
  240. RxQueFormat.Msg = new Byte[RxDataCnt];
  241. // 버퍼 개수만큼 저장
  242. for (int i = 0; i < RxDataCnt; i++)
  243. RxQueFormat.Msg[i] = ReceiveByte[i];
  244. // 메세지큐에 삽입한다
  245. //RxQueue_ADD(RxQueFormat);
  246. // 임시 작업 (추후 삭제)
  247. string Rx = _Convert.DecodingData(_Convert.Coding.UTF8, RxQueFormat.Msg);
  248. ////_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + TxConnect_Socket_Key + ":Rx:" + Rx);
  249. mdi.Event.ClientSocketReceive_SendMessage_Write(Rx);
  250. }
  251. // 특별처리 간혹 소켓을 종료하지 못하고 죽는 서버프로그램도 존재한다
  252. if (RxDataCnt == 0)
  253. {
  254. throw new Exception("server shutdown. not socket close");
  255. }
  256. }
  257. catch (Exception ex)
  258. {
  259. Util.UErrorMessage(ex, 0, 0);
  260. // 로그
  261. //mdi.Event.DebugView_SendMessage_Write("[C]" + ex.ToString());
  262. // 소켓 해제
  263. Socket_Close(TxConnect_Socket_Key);
  264. break;
  265. }
  266. }
  267. }
  268. // 1초 지연후 3초마다 실행되는 스레드 타이머
  269. //public void SocketCheckedTimer_Tick(object d)
  270. //{
  271. //try
  272. //{
  273. // 키값은 소켓의 키:포트
  274. //string TxConnect_Socket_Key = (string)d;
  275. //string[] IP_Port = TxConnect_Socket_Key.Split(':');
  276. // 체크해본다
  277. //if (Ping_SyncCheck(IP_Port[0]) == false || Socket_Status(((Socket)TxConnect_Socket[TxConnect_Socket_Key])) == false)
  278. //{
  279. // 스레드 타이머
  280. //System.Threading.Timer t = (System.Threading.Timer)TxConnect_KeepTimer[TxConnect_Socket_Key];
  281. // 클라이언트가 종료되면 메세지 출력
  282. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + "Disconnected : " + ((Socket)TxConnect_Socket[TxConnect_Socket_Key]).LocalEndPoint + "-" + TxConnect_Socket_Key);
  283. // 해쉬 삭제
  284. //TxConnect_Socket.Remove(TxConnect_Socket_Key);
  285. //TxConnect_KeepTimer.Remove(TxConnect_Socket_Key);
  286. // 소켓 상태 알림 이벤트
  287. //if (SocketConnect_Inform_Event != null) SocketConnect_Inform_Event(TxConnect_Socket_Key, false);
  288. // 스레드 종료
  289. //mdi.Thread.Abort(TxConnect_Socket_Key);
  290. // 타이머종료
  291. //if (t != null)
  292. // t.Dispose();
  293. //}
  294. // }
  295. //catch (Exception ex)
  296. //{
  297. //Util.UErrorMessage(ex, 0, 0);
  298. //}
  299. //}
  300. //
  301. // TX
  302. //
  303. // TX : 메세지 전송 스레드 생성 : 메세지를 생성할때마다 스레드를 발생시키는 방식
  304. public void Socket_Send(string IP, string Port, byte[] Message)
  305. {
  306. // 소켓 생성
  307. EndPointFormat TxQueFormat = new EndPointFormat();
  308. // IP
  309. TxQueFormat.IP = IP;
  310. // PORT
  311. TxQueFormat.Port = Port;
  312. // 버퍼 생성
  313. TxQueFormat.Msg = new Byte[Message.Length];
  314. // 버퍼 저장
  315. TxQueFormat.Msg = Message;
  316. // 스레드 생성
  317. Thread Socket_Send_Thread = new Thread(new ParameterizedThreadStart(Socket_Send_byThread));
  318. // 스레드시작
  319. Socket_Send_Thread.Start(TxQueFormat);
  320. }
  321. // TX : 메세지 전송 스레드 함수 (접속 시도 횟수 없음)
  322. public void Socket_Send_byThread(object QueFormat)
  323. {
  324. // 메세지 전송
  325. EndPointFormat TxQueFormat = (EndPointFormat)QueFormat;
  326. Socket TxSocket = null;
  327. try
  328. {
  329. // 타겟이 접속이 가능한지 체크
  330. TxSocket = Send_Check(TxQueFormat.IP, TxQueFormat.Port, WaitPollTime);
  331. // 가능하다
  332. if (TxSocket != null)
  333. {
  334. // Tx 전송
  335. Send_Data(TxSocket, TxQueFormat);
  336. }
  337. else
  338. {
  339. // LOG
  340. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + TxQueFormat.IP + ":" + TxQueFormat.Port + "전송이 실패합니다");
  341. }
  342. }
  343. catch // (Exception e)
  344. {
  345. // LOG
  346. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + e.ToString());
  347. }
  348. }
  349. // TX : 메세지 전송시 상대방에게 접속가능한지 체크
  350. public Socket Send_Check(string DestIP, string DestPort, int timeoutMs)
  351. {
  352. // 키값은 소켓의 키:포트
  353. string TxConnect_Socket_Key = DestIP + ":" + DestPort;
  354. try
  355. {
  356. // 기존에 사용중인 소켓이 있는 경우에는 그 소켓을 그대로 사용하고 만약 없다면 재생성하도록 한다
  357. if (TxConnect_Socket.ContainsKey(TxConnect_Socket_Key) == true)
  358. {
  359. Socket socket = (Socket)TxConnect_Socket[TxConnect_Socket_Key];
  360. // 기존의 소켓이라고 해도 접속이 끊어져있다면 삭제
  361. if (Ping_SyncCheck(DestIP) == false)
  362. {
  363. // 소켓 해제
  364. Socket_Close(TxConnect_Socket_Key);
  365. return null;
  366. }
  367. else
  368. return socket;
  369. }
  370. else
  371. {
  372. // 상대방에게 접속할수 있는지 알아보기 위한 임시 소켓
  373. Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  374. // 타켓 주소 설정
  375. IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(DestIP), Int32.Parse(DestPort));
  376. //if (Socket_Status(socket) == true)
  377. //{
  378. // 접속시도
  379. socket.Connect(endPoint);
  380. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + "Connected :" + TxConnect_Socket_Key);
  381. // 소켓 테스트 타이머
  382. //System.Threading.Timer SocketCheckedTimer = new System.Threading.Timer(SocketCheckedTimer_Tick, TxConnect_Socket_Key, 1000, 3000);
  383. // 소켓 해쉬 테이블에 추가 (키는 PortNum)
  384. Create_TxConnect_Socket(TxConnect_Socket_Key, socket, null);//SocketCheckedTimer);
  385. // 소켓 상태 알림 이벤트
  386. if (SocketConnect_Inform_Event != null) SocketConnect_Inform_Event(TxConnect_Socket_Key, true);
  387. return socket;
  388. //}
  389. //else
  390. //{
  391. //// 소켓을 삭제
  392. //Delete_TxConnect_Socket(TxConnect_Socket_Key);
  393. //// 로그
  394. ////_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + "Disconnected :" + TxConnect_Socket_Key);
  395. //// 스레드 종료
  396. //_Thread.Abort(TxConnect_Socket_Key);
  397. //// 소켓 상태 알림 이벤트
  398. //if (SocketConnect_Inform_Event != null) SocketConnect_Inform_Event(TxConnect_Socket_Key, true);
  399. //return null;
  400. //}
  401. }
  402. }
  403. catch
  404. {
  405. // 소켓 해제
  406. Socket_Close(TxConnect_Socket_Key);
  407. return null;
  408. }
  409. }
  410. // TX : 메세지 전송
  411. public void Send_Data(Socket TxSocket, EndPointFormat TxQueFormat)
  412. {
  413. // 키값은 소켓의 키:포트
  414. string TxConnect_Socket_Key = TxQueFormat.IP + ":" + TxQueFormat.Port;
  415. try
  416. {
  417. int TxDataCnt = 0;
  418. // 블럭킹모드 사용 (이전에 poll 함수를 통한 블럭킹을 해제시켰음)
  419. TxSocket.Blocking = true;
  420. // 전송
  421. TxDataCnt = TxSocket.Send(TxQueFormat.Msg, 0, TxQueFormat.Msg.Length, 0);
  422. // 전송후 메세지를 정확히 보냈다면!
  423. if (TxDataCnt == TxQueFormat.Msg.Length)
  424. {
  425. // 임시 작업 (추후 삭제)
  426. string Tx = _Convert.DecodingData(_Convert.Coding.UTF8, TxQueFormat.Msg);
  427. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + TxQueFormat.IP + ":" + TxQueFormat.Port + ":Tx:" + Tx);
  428. }
  429. else
  430. {
  431. // LOG
  432. //_Event.DebugView_SendMessage_Write(e.ToString());("[C]" + TxQueFormat.IP + ":" + TxQueFormat.Port + "전송중 실패합니다");
  433. }
  434. }
  435. catch //(Exception e)
  436. {
  437. // 소켓 해제
  438. Socket_Close(TxConnect_Socket_Key);
  439. }
  440. }
  441. //
  442. // Ping 체크 (동기식)
  443. //
  444. public PingOptions options = new PingOptions(); // cyim 2017.01.02 : Memory leak
  445. public bool Ping_SyncCheck(string DestIP)
  446. {
  447. try
  448. {
  449. if (DestIP == null || DestIP.Trim().Length == 0) return false;
  450. using (Ping pingSender = new Ping()) // cyim 2017.01.02 : Memory leak
  451. {
  452. options.DontFragment = true;
  453. string data = "0";
  454. byte[] buffer = Encoding.ASCII.GetBytes(data);
  455. // 2초
  456. PingReply reply = pingSender.Send(DestIP, 500, buffer, options);
  457. if (reply.Status == IPStatus.Success)
  458. {
  459. return true;
  460. }
  461. else
  462. {
  463. return false;
  464. }
  465. }
  466. }
  467. catch (Exception ex)
  468. {
  469. Util.UErrorMessage(ex, 0, 0);
  470. return false;
  471. }
  472. }
  473. // 소켓 해제시 동작
  474. public void Socket_Close(string TxConnect_Socket_Key)
  475. {
  476. try
  477. {
  478. // 소켓을 삭제
  479. Delete_TxConnect_Socket(TxConnect_Socket_Key);
  480. // 소켓 상태 알림 이벤트
  481. if (SocketConnect_Inform_Event != null) SocketConnect_Inform_Event(TxConnect_Socket_Key, false);
  482. // 로그
  483. //if (TxConnect_Socket_ErrLog.Contains(TxConnect_Socket_Key) == false)
  484. // {
  485. // TxConnect_Socket_ErrLog.Add(TxConnect_Socket_Key);
  486. // _Event.DebugView_SendMessage_Write("[C]" + "Disconnected :" + TxConnect_Socket_Key);
  487. //}
  488. // 스레드 종료
  489. mdi.Thread.Abort(TxConnect_Socket_Key);
  490. }
  491. catch (Exception ex)
  492. {
  493. Util.UErrorMessage(ex, 0, 0);
  494. }
  495. }
  496. }
  497. }