C#TCP 简单版通信 服务端

C#TCP 简单版通信 服务端

 public class TcpServer : ITcpServer
    {
        /// 
        /// 锁定对象
        /// 
        private static object LockObject = new object();

        public string Host { get; set; }

        public int Port { get; set; }
        public Action<string> _callBackTcpMessage { get; set; }

        public Socket _Server;

        public Socket _Client;

        public IPAddress Ip;


        /// 
        /// 心跳定时器
        /// 
        private DispatcherTimer _timer1;

        /// 
        /// 报警定时器
        /// 
        private DispatcherTimer _timer2;

        private byte[] byteFixed = new byte[7] { 0xAA, 0xCC, 0x03, 0x06, 0x00, 0x00, 0x00 };
        private byte[] byteSend = new byte[9];

        private Dictionary<int, string> lstUnloadCmd;
        private bool IsFirst = true;
        private TcpServerParm _tcpServerParm;
        public TcpServer()
        {
            _timer1 = new DispatcherTimer();
            _timer1.Interval = TimeSpan.FromMilliseconds(1000);
            _timer1.Tick += TimerReplyHeartbeat;
            _timer1.Start();

            _timer2 = new DispatcherTimer();
            _timer2.Interval = TimeSpan.FromMilliseconds(2000);
            _timer2.Tick += TimerReplyAlarm;
            _timer2.Start();
        }

        public TcpServer(string host, int port)
        {
            this.Host = host;
            this.Port = port;
            // 将将IP地址字符串转换为IPAddress对象
            Ip = IPAddress.Parse(Host);
            // 创建终结点EndPoint
            IPEndPoint ipe = new IPEndPoint(Ip, Port);
            _Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _Server.Bind(ipe);
        }

        public void TcpServerStart(string host, int port)
        {
            this.Host = host;
            this.Port = port;
            // 将将IP地址字符串转换为IPAddress对象
            Ip = IPAddress.Parse(Host);
            // 创建终结点EndPoint
            IPEndPoint ipe = new IPEndPoint(Ip, Port);
            _Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            DeviceAxisStatus.UnloadCmdActionQueue = new Queue<UnloadCmdActionDataModel>();
            lstUnloadCmd = new Dictionary<int, string>();
            for (int i = 1; i <= 96; i++)
            {
                lstUnloadCmd.Add(i, "");
            }
            _Server.Bind(ipe);
        }


        /// 
        /// 开始监听
        /// 
        public void Listen()
        {
            _Server.Listen(1);
            Console.WriteLine("开始监听。。。。");
            _Client = _Server.Accept();
            Console.WriteLine("成功连接客户端");
        }

        /// 
        /// 发送数据
        /// 
        public byte[] Send(byte[] bytes)
        {
            //发送消息给客户端
            _Client.Send(bytes, bytes.Length, 0);
            return bytes;
        }

        /// 
        /// 接收数据
        /// 
        public byte[] Reviced()
        {

            try
            {
                byte[] bytesReviced = new byte[8096];
                int len = _Client.Receive(bytesReviced, 8096, 0);
                Console.WriteLine("接收的客户端消息长度 : {0}", len);
                //将消息转为字符
                return bytesReviced;
            }
            catch (Exception)
            {

                throw;
            }


        }

        private string ByteArrayToString(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
            {
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
            }
            return sb.ToString().ToUpper();
        }

        /// 
        /// 解析数据  
        /// 
        public void ParseData(byte[] bytes)
        {
            var msg = ByteArrayToString(bytes);

            //var length = Convert.ToInt32(msg.Substring(6, 2));
            int length = int.Parse(msg.Substring(6, 2), System.Globalization.NumberStyles.AllowHexSpecifier);
            msg = msg.Substring(0, 12 + length);

           
           
                _callBackTcpMessage?.Invoke(msg);
         

        }

        public byte[] CompleteData(byte byteA, byte byteB)
        {
            byteFixed[2] = byteA;
            byteFixed[6] = byteB;
            var crc = CrcHelper.CalcCRC16(byteFixed);
            var crcByteA = BitConverter.GetBytes(crc);
            Array.Copy(byteFixed, byteSend, 6);
            byteSend[7] = crcByteA[1];
            byteSend[8] = crcByteA[0];
            return byteSend;
        }

        public void StartOpen()
        {
            while (true)
            {
                // 接收到一个消息后  转发出去   应用层协议 
                byte[] bytes = Reviced();
                var msg = ByteArrayToString(bytes);
                msg = msg.Substring(0, 12);
                if (msg != "000000000000")
                {
                    //解析数据
                    ParseData(bytes);
                    Console.WriteLine("从客户端接收到:" + bytes);

                }

            }
        }

        /// 
        /// 主动回复心跳
        /// 
        public void TimerReplyHeartbeat(object sender, EventArgs e)
        {
            byte[] bytes = new byte[7] { 0xAA, 0xCC, 0x03, 0x06, 0x00, 0x00, 0x00 };
        }

        /// 
        /// 主动发送报警
        /// 
        /// 
        /// 
        public void TimerReplyAlarm(object sender, EventArgs e)
        {
        }
    }

你可能感兴趣的:(工业互联网(WPF),c#,tcp/ip,开发语言)