日期:2014-05-20  浏览次数:20877 次

贴一些C#代码 因为公司禁止对外通信
C# code

    public delegate void ExceptionEventHandler(object sender, Exception e);

    public delegate void SocketExceptionEventHandler(object sender, System.Net.Sockets.SocketException e);

    public delegate void ReceiveDataEventHandler(object sender, byte[] data);

    public delegate void SocketCloseEventHandler(object sender,System.Net.Sockets.Socket sock);



C# code

public class Common
    {
        public static IPEndPoint GetEPByName(string HostName,int Port)
        {
            IPEndPoint ep = null;

            foreach (IPAddress ip in Dns.GetHostAddresses(HostName))
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ep = new IPEndPoint(ip, Port);
                    break;
                }
            }

            return ep;
        }

        /// <summary>
        /// 使用已连接的Socket接收数据
        /// </summary>
        /// <param name="sock">已连接的Socket</param>
        /// <param name="ReceiveLength">将要接收的数据长度</param>
        /// <returns>返回接受到的数据,若对方关闭连接则返回null</returns>
        public static byte[] ReceiveData(Socket sock,int ReceiveLength)
        { 
            byte[] buff = new byte[ReceiveLength];
            int readbytes = 0;
            try
            {
                while (ReceiveLength != 0)
                {
                    readbytes = sock.EndReceive(sock.BeginReceive(buff, buff.Length - ReceiveLength, ReceiveLength, SocketFlags.None, null, null));
                    if (readbytes <= 0)
                        return new byte[0];
                    ReceiveLength -= readbytes;
                }
                return buff;
            } catch (Exception e){ throw e; }
        }

        /// <summary>
        /// 使用已连接的Socket发送数据
        /// </summary>
        /// <param name="sock">已连接的Socket</param>
        /// <param name="data">将要发送的数据</param>
        /// <returns>返回数据是否发送成功</returns>
        public static bool SendData(Socket sock,byte[] data)
        {
            int SendLength = 0;
            int sendbytes = 0;
            try
            {
                while (SendLength != data.Length)
                {
                    sendbytes = sock.EndSend(sock.BeginSend(data, SendLength, data.Length - SendLength, SocketFlags.None, null, null));
                    if (sendbytes <= 0)
                        return false;
                    SendLength += sendbytes;
                }
                return true;
            } catch (Exception e) { throw e; }
        }

    }



C# code

public class Listener
    {

        public event ExceptionEventHandler OnException;

        public event ReceiveDataEventHandler OnReceiveData;

        public event SocketExceptionEventHandler OnSocketException;

        public event SocketCloseEventHandler OnSocketClose;

        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        public Listener()
        {
            OnSocketClose += new SocketCloseEventHandler(Listener_OnSocketClose);
        }
        /// <summary>
        /// 这个方法或许不对,有疑问
        /// </summary>
        public void StopListening()
        {
            listener.Close();
        }


        public void StartListening(int Port,int backlog)
        {
            try
            {
                listener.Bind(Common.GetEPByName(Environment.MachineName, Port));
                listener.Listen(backlog);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

            }
            catch (SocketException e)
            {
                if (OnSocketException != null)
                    OnSocketException(this, e);
            }
            catch (Exception e)
            {
                if (OnException != null)
                    OnException(this, e);
            }
        }

        void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);


                while (true)
                {
                    byte[] LengthBuff = Common.ReceiveData(handler, 4);
                    if (LengthBuff.Length == 0)
                        OnSocketClose(this, handler);
                    byte[] DataBuff = Common.ReceiveData(handler, BitConverter.ToInt32(LengthBuff, 0));
                    if (DataBuff.Length == 0)
                        OnSocketClose(this, handler);
                    if (OnReceiveData != null)
                        OnReceiveData(this, DataBuff);
                }

            }
            catch (SocketException e)
            {
                if (OnSocketException != null)
                    OnSocketException(this, e);
            }
            catch (Exception e)
            {
                if (OnException != null)
                    OnException(this, e);
            }
        }

        void Listener_OnSocketClose(object sender, Socket sock)
        {
            try
            {
                sock.Shutdown(SocketShutdown.Both);
            }
            finally
            {
                sock.Close();
            }
        }


        

    }