using System;
using System.Collections.Generic;
using System.Text;

namespace SocketsTCPIP
{
    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    using System.Text;

    public static class CClientTCPIP
    {
        static int _initCount = 0;
        static bool _ifInit = false;
        static string _remoteIP;
        static int _remotePort;
        static Socket clientSocket=null;
        static EndPoint epServer;
        static byte[] _byteData = new byte[6];
        static string _tcpError;

        public static string TcpError
        {
            get { return _tcpError; }
            set { _tcpError = value; }
        }
        public static byte[] ByteData
        {
            get { return _byteData; }
            set { _byteData = value; }
        }


        public static bool InitClientTCPIP(string remoteIP, int remotePort)
        {
            if (_initCount > 3)
            {
                _tcpError = "连接远程主机时，发生三次连接失败错误！请检查远程主机是否正常运行!重新启动本系统。";
                _ifInit = false;
                return false;
            }

            // Connect to a remote device.
            try
            {
                _remoteIP = remoteIP;
                _remotePort = remotePort;
                // Establish the remote endpoint for the socket.
                IPAddress ipAddress = IPAddress.Parse(_remoteIP);

                IPEndPoint remoteEP = new IPEndPoint(ipAddress, _remotePort);

                //IPAddress iplocal = IPAddress.Parse("192.168.1.4");

                //IPEndPoint EPlocal = new IPEndPoint(iplocal, 1050);

                epServer = (EndPoint)remoteEP;

                // Create a TCP/IP socket.
                if (clientSocket == null)
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);

                }
                //clientSocket.Bind((EndPoint)EPlocal);
                // Connect to the remote endpoint.
                clientSocket.BeginConnect(epServer,
                    new AsyncCallback(ConnectCallback), clientSocket);
                _ifInit = true;
                return true;

            }
            catch (Exception e)
            {
                if (_initCount > 3)
                {
                    _tcpError = "连接远程主机时，发生三次连接失败错误！请检查远程主机是否正常运行!重新启动本系统。";
                    clientSocket = null;
                    return false;
                }
                _initCount++;
                _ifInit = false;

                _tcpError = e.Message;
                return false;
            }
        }

        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket sk = (Socket)ar.AsyncState;

                // Complete the connection.
                sk.EndConnect(ar);
            }
            catch (Exception e)
            {
                _tcpError = e.Message;
                _ifInit = false;
            }
        }

        public static byte[] Receive(string remoteIP, int remotePort)
        {
            try
            {
                if (_ifInit == false)
                {
                    if (InitClientTCPIP(remoteIP, remotePort) == false) return null;
                }
                

                // Begin receiving the data from the remote device.
                clientSocket.BeginReceive(_byteData, 0, _byteData.Length, 0,
                    new AsyncCallback(ReceiveCallback), clientSocket);

                return _byteData;
            }
            catch (Exception e)
            {
                _ifInit = false;
                _tcpError = e.Message;
                return null;
            }
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket 
                
                Socket client = (Socket)ar.AsyncState;
                //System.Threading.Thread.Sleep(10);
                // Read data from the remote device.
                client.EndReceive(ar);
                //clientSocket.BeginReceive(_byteData, 0, _byteData.Length, 0,
                //    new AsyncCallback(ReceiveCallback), client);

            }
            catch (Exception e)
            {
                _ifInit = false;
                _tcpError = e.Message;
            }
        }

        public static bool  Send(string remoteIP, int remotePort,byte[] data)
        {
            try
            {
                if (_ifInit == false)
                {
                    if (InitClientTCPIP(remoteIP, remotePort) == false)
                    {
                        return false;
                    }
                }
                byte[] byteData = data;

                // Begin sending the data to the remote device.
                clientSocket.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), clientSocket);
                
                return true;
            }
            catch (Exception e)
            {
                _ifInit = false;
                _tcpError = e.Message;
                return false;
            }
        }

        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                client.EndSend(ar);

            }
            catch (Exception e)
            {
                _ifInit = false;
                _tcpError = e.Message;


            }
        }


    }
 

}
