1. 程式人生 > 實用技巧 >Socket多次連線

Socket多次連線

 1        private static byte[] result = new byte[1024];
 2         /// <summary>
 3         /// HL7串通過socket傳送到VP
 4         /// </summary>
 5         /// <param name="msg"></param>
 6         /// <returns></returns>
 7         public static string sendhl7(string msg, int sendingTimes)
8 { 9 10 while (sendingTimes < 3) 11 { 12 Thread.Sleep(100); //等待0.1秒鐘 13 sendingTimes++; 14 var socketIP = System.Configuration.ConfigurationManager.AppSettings["socketIP"]; 15 var socketPort = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["
socketPort"]); 16 //設定伺服器IP地址 17 IPAddress ip = IPAddress.Parse(socketIP); 18 Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 19 int error = 0; 20 try 21 { 22
clientSocket.Connect(new IPEndPoint(ip, socketPort)); //配置伺服器IP與埠 23 error++; 24 clientSocket.Send(Encoding.UTF8.GetBytes(msg)); 25 int receiveL = clientSocket.Receive(result); 26 LogManager.WriteLog("" + sendingTimes + "次連線VP的socket服務傳送訊息成功", Encoding.UTF8.GetString(result, 0, receiveL)); 27 clientSocket.Close(); 28 return Encoding.UTF8.GetString(result, 0, receiveL); 29 } 30 31 catch (Exception ex) 32 { 33 LogManager.WriteLog("" + sendingTimes + "次給VP的socket服務傳訊息報錯", ex.ToString()); 34 if (error == 0) 35 { 36 LogManager.WriteLog("連線VP的socket服務", "" + sendingTimes + "次連線失敗! 連線資訊 " + msg); 37 } 38 if (error == 1) 39 { 40 LogManager.WriteLog("給VP的socket服務 第" + sendingTimes + "次傳送訊息報錯", "連線資訊: " + msg); 41 } 42 if (clientSocket != null && clientSocket.Connected) 43 { 44 clientSocket.Shutdown(SocketShutdown.Both); 45 clientSocket.Close(); 46 } 47 continue; 48 } 49 } 50 return ""; 51 }