HttpServer.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Dynamic;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. using UAS_MES_NEW.DataOperate;
  14. using UAS_MES_NEW.Entity;
  15. namespace UAS_MES_NEW.PublicMethod
  16. {
  17. public class BindItem
  18. {
  19. [JsonProperty("bindKey")]
  20. public string BindKey { get; set; }
  21. [JsonProperty("bindValue")]
  22. public string BindValue { get; set; }
  23. [JsonProperty("keyType")]
  24. public string KeyType { get; set; }
  25. [JsonProperty("keyValue")]
  26. public string KeyValue { get; set; }
  27. [JsonProperty("hashType")]
  28. public string HashType { get; set; }
  29. [JsonProperty("hashKey")]
  30. public string HashKey { get; set; }
  31. }
  32. public class RootObject
  33. {
  34. [JsonProperty("productModuleType")]
  35. public string ProductModuleType { get; set; }
  36. [JsonProperty("productMainClass")]
  37. public string ProductMainClass { get; set; }
  38. [JsonProperty("productMediumClass")]
  39. public string ProductMediumClass { get; set; }
  40. [JsonProperty("productSubClass")]
  41. public string ProductSubClass { get; set; }
  42. [JsonProperty("task")]
  43. public string Task { get; set; }
  44. [JsonProperty("processType")]
  45. public string ProcessType { get; set; }
  46. [JsonProperty("userId")]
  47. public string UserId { get; set; }
  48. [JsonProperty("bindList")]
  49. public List<BindItem> BindList { get; set; }
  50. }
  51. public class DeviceInfo
  52. {
  53. [JsonProperty("tool_name")]
  54. public string ToolName { get; set; }
  55. [JsonProperty("response")]
  56. public string Response { get; set; }
  57. [JsonProperty("status")]
  58. public int Status { get; set; }
  59. [JsonProperty("product_name")]
  60. public string ProductName { get; set; }
  61. [JsonProperty("product_mode")]
  62. public string ProductMode { get; set; }
  63. [JsonProperty("material_code")]
  64. public string MaterialCode { get; set; }
  65. [JsonProperty("batch_no")]
  66. public string BatchNo { get; set; }
  67. [JsonProperty("production_date")]
  68. public string ProductionDate { get; set; }
  69. [JsonProperty("big_box_no")]
  70. public string BigBoxNo { get; set; }
  71. [JsonProperty("box_no")]
  72. public string BoxNo { get; set; }
  73. [JsonProperty("reserve10")]
  74. public string Reserve10 { get; set; }
  75. [JsonProperty("packing_num")]
  76. public int PackingNum { get; set; }
  77. [JsonProperty("soft_version")]
  78. public string SoftVersion { get; set; }
  79. [JsonProperty("hd_version")]
  80. public string HdVersion { get; set; }
  81. [JsonProperty("voltage")]
  82. public string Voltage { get; set; }
  83. [JsonProperty("power")]
  84. public string Power { get; set; }
  85. [JsonProperty("order_no")]
  86. public string OrderNo { get; set; }
  87. // 使用字典或列表来存储序列化的数组数据
  88. public List<string> DSN { get; set; } = new List<string>();
  89. public List<string> MacStart { get; set; } = new List<string>();
  90. public List<string> MacEnd { get; set; } = new List<string>();
  91. public List<string> DeviceId { get; set; } = new List<string>();
  92. public List<string> DevEnNo { get; set; } = new List<string>();
  93. public List<string> Reserve3 { get; set; } = new List<string>();
  94. public List<string> Reserve4 { get; set; } = new List<string>();
  95. }
  96. public class DeviceInfoConverter : JsonConverter<DeviceInfo>
  97. {
  98. public override DeviceInfo ReadJson(JsonReader reader, System.Type objectType, DeviceInfo existingValue, bool hasExistingValue, JsonSerializer serializer)
  99. {
  100. JObject jsonObject = JObject.Load(reader);
  101. DeviceInfo deviceInfo = new DeviceInfo();
  102. // 解析基本字段
  103. serializer.Populate(jsonObject.CreateReader(), deviceInfo);
  104. // 解析数组字段
  105. ParseArrayFields(jsonObject, deviceInfo);
  106. return deviceInfo;
  107. }
  108. public override void WriteJson(JsonWriter writer, DeviceInfo value, JsonSerializer serializer)
  109. {
  110. throw new NotImplementedException();
  111. }
  112. private void ParseArrayFields(JObject jsonObject, DeviceInfo deviceInfo)
  113. {
  114. int index = 0;
  115. // 解析 d_sn 数组
  116. while (true)
  117. {
  118. string key = $"d_sn{index}";
  119. if (jsonObject.TryGetValue(key, out JToken value))
  120. {
  121. deviceInfo.DSN.Add(value.ToString());
  122. index++;
  123. }
  124. else
  125. {
  126. break;
  127. }
  128. }
  129. // 解析 mac_start 数组
  130. index = 0;
  131. while (true)
  132. {
  133. string key = $"mac_start{index}";
  134. if (jsonObject.TryGetValue(key, out JToken value))
  135. {
  136. deviceInfo.MacStart.Add(value.ToString());
  137. index++;
  138. }
  139. else
  140. {
  141. break;
  142. }
  143. }
  144. // 解析 mac_end 数组
  145. index = 0;
  146. while (true)
  147. {
  148. string key = $"mac_end{index}";
  149. if (jsonObject.TryGetValue(key, out JToken value))
  150. {
  151. deviceInfo.MacEnd.Add(value.ToString());
  152. index++;
  153. }
  154. else
  155. {
  156. break;
  157. }
  158. }
  159. // 解析 dev_en_no 数组
  160. index = 0;
  161. while (true)
  162. {
  163. string key = $"dev_en_no{index}";
  164. if (jsonObject.TryGetValue(key, out JToken value))
  165. {
  166. deviceInfo.DevEnNo.Add(value.ToString());
  167. index++;
  168. }
  169. else
  170. {
  171. break;
  172. }
  173. }
  174. // 解析 reserve3 数组
  175. index = 0;
  176. while (true)
  177. {
  178. string key = $"reserve3_{index}";
  179. if (jsonObject.TryGetValue(key, out JToken value))
  180. {
  181. deviceInfo.Reserve3.Add(value.ToString());
  182. index++;
  183. }
  184. else
  185. {
  186. break;
  187. }
  188. }
  189. // 解析 reserve4 数组
  190. index = 0;
  191. while (true)
  192. {
  193. string key = $"reserve4_{index}";
  194. if (jsonObject.TryGetValue(key, out JToken value))
  195. {
  196. deviceInfo.Reserve4.Add(value.ToString());
  197. index++;
  198. }
  199. else
  200. {
  201. break;
  202. }
  203. }
  204. // 解析 DeviceId 数组
  205. index = 0;
  206. while (true)
  207. {
  208. string key = $"DeviceId{index}";
  209. if (jsonObject.TryGetValue(key, out JToken value))
  210. {
  211. deviceInfo.DeviceId.Add(value.ToString());
  212. index++;
  213. }
  214. else
  215. {
  216. break;
  217. }
  218. }
  219. }
  220. }
  221. public class HttpServer
  222. {
  223. static DataHelper dh = new DataHelper();
  224. public static int SN_SERVICE_PORT = 8234;
  225. public static int MAX_BUF_SIZE = 4096;
  226. static string ComputeSha256Hash(string input)
  227. {
  228. using (SHA256 sha256 = SHA256.Create())
  229. {
  230. byte[] bytes = Encoding.UTF8.GetBytes(input);
  231. byte[] hashBytes = sha256.ComputeHash(bytes);
  232. StringBuilder builder = new StringBuilder();
  233. for (int i = 0; i < hashBytes.Length; i++)
  234. {
  235. builder.Append(hashBytes[i].ToString("x2"));
  236. }
  237. return builder.ToString().ToUpper();
  238. }
  239. }
  240. //获取SN的EN号,彩盒标机身标一个工站一起打印,需要SN单个获取
  241. public static void GetEN(string iSN)
  242. {
  243. DataTable dt = (DataTable)dh.ExecuteSql("select ms_makecode,pr_prefix,pr_prebigxbox,pr_regcode from makeserial left join product on ms_prodcode=pr_code where ms_sncode ='" + iSN + "' order by ms_id desc", "select");
  244. string prefix = "";
  245. string regcode = "";
  246. string makecode = "";
  247. if (dt.Rows.Count > 0)
  248. {
  249. prefix = dt.Rows[0]["pr_prefix"].ToString();
  250. regcode = dt.Rows[0]["pr_regcode"].ToString();
  251. makecode = dt.Rows[0]["ms_makecode"].ToString();
  252. }
  253. dynamic obj = new ExpandoObject();
  254. obj.tool_name = "zte";
  255. obj.request = "Storage2";
  256. obj.User = "mes";
  257. obj.password = "258456";
  258. obj.po_sn = iSN;
  259. obj.wholeDeviceCode = "";
  260. obj.reg_code = regcode;
  261. obj.prefix_en_no = prefix;
  262. obj.prefix_big_box = "";
  263. obj.packing_num = "";
  264. obj.isn = prefix;
  265. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  266. string returnstr = SendData(json);
  267. JObject deviceObj = JObject.Parse(returnstr);
  268. string WholeDeviceCode = deviceObj["WholeDeviceCode"].ToString();
  269. string SN = deviceObj["SN"].ToString();
  270. string dev_en_no = deviceObj["dev_en_no"].ToString();
  271. string mac = deviceObj["mac"].ToString();
  272. string mac_start = deviceObj["mac_start"].ToString();
  273. string mac_end = deviceObj["mac_end"].ToString();
  274. string reg_code = deviceObj["reg_code"].ToString();
  275. string reserve3 = deviceObj["reserve3"].ToString();
  276. string device_type = deviceObj["device_type"].ToString();
  277. string en_no = deviceObj["en_no"].ToString();
  278. dh.ExecuteSql("insert into ZTEDATA(ZD_ID,ZD_D_SN,zd_WholeDeviceCode,ZD_DEV_EN_NO,ZD_SN, ZD_MAKECODE, ZD_TYPE, ZD_VALUE,zd_mac,ZD_MAC_START, ZD_MAC_END,ZD_RESERVE3,zd_enno,zd_devicetype,zd_regcode)" +
  279. "values(ZTEDATA_seq.nextval,'" + SN + "','" + WholeDeviceCode + "','" + dev_en_no + "','" + iSN + "','" + makecode + "','彩盒机身标','','" + mac + "','" + mac_start + "','" + mac_end + "','" + reserve3 + "','" + en_no + "','" + device_type + "','" + reg_code + "')", "insert");
  280. Console.WriteLine(json);
  281. }
  282. //发送外箱号数据,打印前获取
  283. public static void SendBoxData(string iBox)
  284. {
  285. string sn = dh.getFieldDataByCondition("packagedetail", "replace(wm_concat(pd_barcode),',','-')", "pd_outboxcode='" + iBox + "'").ToString();
  286. DataTable dt = (DataTable)dh.ExecuteSql("select pr_custmachinetype,ms_makecode from makeserial left join product on ms_prodcode=pr_code where ms_outboxcode ='" + iBox + "' order by ms_id desc", "select");
  287. string pr_custmachinetype = "";
  288. string makecode = "";
  289. if (dt.Rows.Count > 0)
  290. {
  291. pr_custmachinetype = dt.Rows[0]["pr_custmachinetype"].ToString();
  292. makecode = dt.Rows[0]["ms_makecode"].ToString();
  293. }
  294. var root = new RootObject
  295. {
  296. ProductModuleType = "整机",
  297. ProductMainClass = "固网_CPE",
  298. ProductMediumClass = "CPE",
  299. ProductSubClass = pr_custmachinetype,
  300. Task = makecode,
  301. ProcessType = "生产过程",
  302. UserId = User.UserName,
  303. BindList = new List<BindItem>()
  304. };
  305. root.BindList.Add(new BindItem
  306. {
  307. BindKey = "cartonSn",
  308. BindValue = iBox,
  309. KeyType = "macbox",
  310. KeyValue = sn,
  311. HashType = "SHA256",
  312. HashKey = ComputeSha256Hash(sn)
  313. });
  314. dt = (DataTable)dh.ExecuteSql("select pd_barcode from packagedetail pd_outboxcode='" + iBox + "'", "select");
  315. for (int i = 0; i < dt.Rows.Count; i++)
  316. {
  317. root.BindList.Add(new BindItem
  318. {
  319. BindKey = "mac",
  320. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  321. KeyType = "EN",
  322. KeyValue = "4Y12R9300001",
  323. HashType = "NON-HASH",
  324. HashKey = "4Y12R9300001"
  325. });
  326. root.BindList.Add(new BindItem
  327. {
  328. BindKey = "mac",
  329. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  330. KeyType = "电源条码",
  331. KeyValue = "1U1Y2505100013640",
  332. HashType = "NON-HASH",
  333. HashKey = "1U1Y2505100013640"
  334. });
  335. root.BindList.Add(new BindItem
  336. {
  337. BindKey = "mac",
  338. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  339. KeyType = "JY-License",
  340. KeyValue = "Qk1K4rmuowTDl+NEtSIeHx1td6Tzzm0wDrw/AMCvJ6mrXQ5wsSgoxia+T5Cj+uH4xrGUrjGrZvh/WUQN88iDrPO7kuTA0mvo/Ay+AsFJYnn00JQYQkN9ul+a+Qh0EPBqCVa4ikllHcD1Pqq4Eubs6XXNFhKOtK7F7FMotfGzzAVg7RhKVoVRVFcK6ubSVWXW+SnGx5muH+WZPaiHLjt+kxBR8tZJuBl1LQvMWP74JSWKkcFWwcWlARnCJePvRTvKTDd5e7q9rpBpAc7Z79XYQ6Fs4eXM44O6/hA88YW/BK0TZq3AaaMxH8BpJnwZt4lIyuqXispeaB2eieFBR0JwWg==",
  341. HashType = "SHA256",
  342. HashKey = ComputeSha256Hash(sn),
  343. }); ;
  344. }
  345. string json = JsonConvert.SerializeObject(root, Formatting.Indented);
  346. string returnstr = SendData(json);
  347. Console.WriteLine(json);
  348. }
  349. //获取外箱号信息
  350. public static void GetOutBoxInfo(string iBox)
  351. {
  352. dynamic obj = new ExpandoObject();
  353. var expandoDict = obj as IDictionary<string, object>;
  354. DataTable dt = (DataTable)dh.ExecuteSql("select pd_barcode,pd_makecode from packagedetail where pd_outboxcode='" + iBox + "'", "select");
  355. string makecode = "";
  356. for (int i = 0; i < dt.Rows.Count; i++)
  357. {
  358. string enNoKey = $"en_no{i}";
  359. string enNoValue = dt.Rows[i]["pd_barcode"].ToString();
  360. expandoDict[enNoKey] = enNoValue;
  361. makecode = dt.Rows[i]["pd_makecode"].ToString();
  362. }
  363. obj.request = "Q_wai_xiang";
  364. obj.packing_num = 20;
  365. obj.User = "mes";
  366. obj.po_sn = makecode;
  367. obj.password = "258456";
  368. obj.tool_name = "zte";
  369. obj.noType = 0;
  370. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  371. string returnstr = SendData(json);
  372. var settings = new JsonSerializerSettings
  373. {
  374. Converters = new List<JsonConverter> { new DeviceInfoConverter() }
  375. };
  376. DeviceInfo deviceInfo = JsonConvert.DeserializeObject<DeviceInfo>(returnstr, settings);
  377. for (int i = 0; i < deviceInfo.DSN.Count; i++)
  378. {
  379. Console.WriteLine($"设备 {i}:");
  380. Console.WriteLine($" 序列号: {deviceInfo.DSN[i]}");
  381. Console.WriteLine($" MAC起始: {deviceInfo.MacStart[i]}");
  382. Console.WriteLine($" MAC结束: {deviceInfo.MacEnd[i]}");
  383. Console.WriteLine($" 设备编码: {deviceInfo.DevEnNo[i]}");
  384. Console.WriteLine($" 预留3: {deviceInfo.Reserve3[i]}");
  385. }
  386. //将返回的信息存入数据库
  387. for (int i = 0; i < deviceInfo.DSN.Count; i++)
  388. {
  389. dh.ExecuteSql("insert into ZTEDATA(ZD_ID,ZD_SN, ZD_MAKECODE, ZD_TYPE, ZD_VALUE,ZD_product_mode, ZD_PRODUCTNAME, ZD_MATERIAL_CODE, ZD_BATCH_NO, ZD_SOFT_VERSION, ZD_HD_VERSION, " +
  390. "ZD_VOLTAGE, ZD_POWER, ZD_ORDER_NO, ZD_BIG_BOX_NO, ZD_D_SN, ZD_DEV_EN_NO, ZD_RESERVE3, ZD_DEVICEID, ZD_MAC_START, ZD_MAC_END,zd_production_date, ZD_INDATE)" +
  391. "values(ZTEDATA_seq.nextval,'" + deviceInfo.DSN[i] + "','','BOX','','" + deviceInfo.ProductName + "','" + deviceInfo.ProductName + "','" + deviceInfo.MaterialCode + "','" + deviceInfo.BatchNo + "','" + deviceInfo.SoftVersion + "','" + deviceInfo.HdVersion + "'," +
  392. "'" + deviceInfo.Voltage + "','" + deviceInfo.Power + "','" + deviceInfo.OrderNo + "','" + deviceInfo.BigBoxNo + "','" + deviceInfo.DSN[i] + "'," +
  393. "'" + deviceInfo.Reserve3[i] + "','" + deviceInfo.DeviceId[i] + "','" + deviceInfo.MacStart[i] + "','" + deviceInfo.MacEnd[i] + "','" + deviceInfo.ProductionDate + "',sysdate)", "insert");
  394. }
  395. Console.WriteLine(json);
  396. }
  397. //获取栈板信息
  398. public static void GetPalletInfo(string iBox)
  399. {
  400. DataTable dt = (DataTable)dh.ExecuteSql("select pa_outboxcode,pa_makecode from package where pa_mothercode='" + iBox + "'", "select");
  401. dynamic obj = new ExpandoObject();
  402. var expandoDict = obj as IDictionary<string, object>;
  403. string makecode = "";
  404. for (int i = 0; i < dt.Rows.Count; i++)
  405. {
  406. string enNoKey = $"big_box_no{i}";
  407. string enNoValue = dt.Rows[i]["pa_outboxcode"].ToString();
  408. expandoDict[enNoKey] = enNoValue;
  409. makecode = dt.Rows[i]["pa_makecode"].ToString();
  410. }
  411. obj.request = "pallet";
  412. obj.packing_num = dt.Rows.Count;
  413. obj.User = "mes";
  414. obj.po_sn = makecode;
  415. obj.password = "258456";
  416. obj.tool_name = "zte";
  417. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  418. string returnstr = SendData(json);
  419. Console.WriteLine(returnstr);
  420. Console.WriteLine(json);
  421. }
  422. //发送数据
  423. public static string SendData(string json)
  424. {
  425. string serverIP = "10.1.162.175";
  426. int port = 8234;
  427. try
  428. {
  429. TcpClient client = new TcpClient();
  430. client.Connect(serverIP, port);
  431. NetworkStream stream = client.GetStream();
  432. // 发送数据
  433. byte[] data = Encoding.UTF8.GetBytes(json);
  434. stream.Write(data, 0, data.Length);
  435. Console.WriteLine($"已发送请求: {json}");
  436. // 接收响应 - 使用安全的方式
  437. return ReceiveDataSafely(stream);
  438. }
  439. catch (Exception ex)
  440. {
  441. Console.WriteLine($"错误: {ex.Message}");
  442. return "";
  443. }
  444. }
  445. private static string ReceiveDataSafely(NetworkStream stream)
  446. {
  447. MemoryStream ms = new MemoryStream();
  448. byte[] buffer = new byte[1024];
  449. int totalBytesRead = 0;
  450. const int MAX_SIZE = 10 * 1024 * 1024;
  451. try
  452. {
  453. stream.ReadTimeout = 5000;
  454. while (true)
  455. {
  456. int bytesRead = stream.Read(buffer, 0, buffer.Length);
  457. if (bytesRead == 0) break;
  458. ms.Write(buffer, 0, bytesRead);
  459. totalBytesRead += bytesRead;
  460. Console.WriteLine($"本次读取: {bytesRead} 字节, 累计: {totalBytesRead} 字节");
  461. if (totalBytesRead > MAX_SIZE)
  462. {
  463. throw new Exception($"接收数据超过大小限制: {MAX_SIZE} 字节");
  464. }
  465. if (!stream.DataAvailable)
  466. {
  467. Thread.Sleep(100);
  468. if (!stream.DataAvailable) break;
  469. }
  470. }
  471. byte[] receivedData = ms.ToArray();
  472. // 直接使用GBK编码(最常用的中文编码)
  473. Encoding chineseEncoding = Encoding.GetEncoding("GBK");
  474. string response = chineseEncoding.GetString(receivedData);
  475. Console.WriteLine($"使用GBK编码的响应: {response}");
  476. return response;
  477. }
  478. catch (TimeoutException)
  479. {
  480. byte[] partialData = ms.ToArray();
  481. Encoding chineseEncoding = Encoding.GetEncoding("GBK");
  482. string partialResponse = chineseEncoding.GetString(partialData);
  483. Console.WriteLine($"接收超时,已接收数据: {partialResponse}");
  484. return partialResponse;
  485. }
  486. }
  487. public static readonly uint PROTOCOL_FLAG = 0x4C4F4F54;
  488. public static byte[] BuildPacket(string jsonData)
  489. {
  490. if (string.IsNullOrEmpty(jsonData))
  491. {
  492. throw new ArgumentException("JSON数据不能为空");
  493. }
  494. using (MemoryStream ms = new MemoryStream())
  495. {
  496. // 1. 写入flag (小端序)
  497. byte[] flagBytes = BitConverter.GetBytes(PROTOCOL_FLAG);
  498. ms.Write(flagBytes, 0, 4);
  499. // 2. 将JSON字符串转换为UTF8字节数组
  500. byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
  501. // 3. 写入data_len (小端序)
  502. byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
  503. ms.Write(lengthBytes, 0, 4);
  504. // 4. 写入data
  505. ms.Write(jsonBytes, 0, jsonBytes.Length);
  506. return ms.ToArray();
  507. }
  508. }
  509. public static string ToServerReq(string strJSON)
  510. {
  511. int nRet = 0;
  512. string strServerIP = "10.1.162.175";
  513. string strResp = "";
  514. IPAddress ip = IPAddress.Parse(strServerIP);
  515. Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  516. while (true)
  517. {
  518. try
  519. {
  520. clientSocket.Connect(new IPEndPoint(ip, SN_SERVICE_PORT));
  521. }
  522. catch
  523. {
  524. nRet = -13;
  525. break;
  526. }
  527. try
  528. {
  529. FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(null);
  530. byte[] bytJson = Encoding.UTF8.GetBytes(strJSON); //Encoding.ASCII.GetBytes(strJSON);
  531. stHead.setDataLen(bytJson.Length);
  532. byte[] bytBuf = new byte[FACT_DATA_HEAD.MY_LEN + bytJson.Length];
  533. byte[] bytSrcHead = stHead.getBytes();
  534. Array.Copy(bytSrcHead, 0, bytBuf, 0, bytSrcHead.Length);
  535. Array.Copy(bytJson, 0, bytBuf, FACT_DATA_HEAD.MY_LEN, bytJson.Length);
  536. clientSocket.Send(bytBuf);
  537. }
  538. catch
  539. {
  540. nRet = -12;
  541. break;
  542. }
  543. //判定接口回传的flag和本地传过去的是否一致
  544. byte[] bytRecv = new byte[MAX_BUF_SIZE];
  545. int nRecvSize = 0, nSize = 0;
  546. nRecvSize = clientSocket.Receive(bytRecv, 0, FACT_DATA_HEAD.MY_LEN, SocketFlags.None);
  547. // string strTmp;
  548. // strTmp = string.Format("clientSocket.Receive={0}", nRecvSize);
  549. // Trace.WriteLine(strTmp);
  550. if (nRecvSize > 0)
  551. {
  552. FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(bytRecv);
  553. Console.WriteLine(stHead.getFlag());
  554. Console.WriteLine(FACT_DATA_HEAD.PROTOCOL_FLAG);
  555. if (stHead.getFlag() == FACT_DATA_HEAD.PROTOCOL_FLAG)
  556. {
  557. int nPos = 0;
  558. nSize = stHead.getDatalen();
  559. while (nPos < nSize)
  560. {
  561. nRecvSize = clientSocket.Receive(bytRecv, nPos, 1869881979 - nPos, SocketFlags.None);
  562. if (nRecvSize < 0)
  563. {
  564. nRet = -14;
  565. break;
  566. }
  567. nPos += nRecvSize;
  568. }
  569. strResp = Encoding.Default.GetString(bytRecv, 0, nSize);
  570. }
  571. else nRet = -11;
  572. }
  573. else nRet = -10;
  574. break;
  575. }
  576. if (nRet > -13) clientSocket.Shutdown(SocketShutdown.Both);
  577. clientSocket.Close();
  578. return strResp;
  579. }
  580. }
  581. }