using Hanhe.iWCS.Common; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; namespace HH.WCS.JingmenGEMNorthProtocol { public class TcpServer { public static Dictionary clients = new Dictionary(); public static Dictionary buffers = new Dictionary(); /// /// 重连PLC /// /// /// public static void ReConnect(string ip,int port) { Console.WriteLine($"设备重连:ip:{ip},Port:{port}"); if (clients.Keys.Contains(ip)) { // 关闭socket clients[ip].Close(); clients.Remove(ip); Console.WriteLine($"Close Tcp :{ip},Port:{port}"); } // 创建一个socket对象 Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); try { // 连接到远程IP socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port)); if (clients.Keys.Contains(ip)) clients[ip] = socket; else clients.Add(ip, socket); if (!buffers.Keys.Contains(ip)) buffers.Add(ip, new byte[1024]); Console.WriteLine($"重连成功:ip:{ip},Port:{port}"); } catch (SocketException ex) { Console.WriteLine("Error: " + ex.Message); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } public static bool SendTcpMsg(string ip, int port, string msg) { try { //根据ip找到目标端口 CMMLog.Info($"【SendTcpMsg】,ip:{ip},port:{port},msg:{msg}"); if (clients.Keys.Contains(ip)) { CMMLog.Info("【SendTcpMsg】 111111"); var client = clients[ip]; client.ReceiveTimeout = 200; if (client.Connected) { CMMLog.Info("【SendTcpMsg】 2222222222"); try { CMMLog.Info("【SendTcpMsg】 33333333"); //byte[] messageBytes = Encoding.UTF8.GetBytes(msg); byte[] messageBytes = Hex2Bytes(msg); CMMLog.Info("【SendTcpMsg】 4444444444"); client.Send(messageBytes); CMMLog.Info("【SendTcpMsg】 5555555555"); Console.WriteLine("Send data: " + msg); return true; } catch (SocketException ex) { CMMLog.Info("【SendTcpMsg】 66666666"); Console.WriteLine(ex.Message); //clients[ip].Close(); clients.Remove(ip); } } else { //clients[ip].Close(); clients.Remove(ip); } } else { CMMLog.Info("【SendTcpMsg】 777777777777"); Console.WriteLine("未找到设备的链接:" + ip); ReConnect(ip, port); SendTcpMsg(ip, port, msg); } } catch(Exception ex) { Console.WriteLine("err :"+ex.Message); } return false; } internal static byte[] Hex2Bytes(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } } }