码迷,mamicode.com
首页 > Windows程序 > 详细

C# Socket的安全关闭

时间:2018-04-05 16:28:45      阅读:327      评论:0      收藏:0      [点我收藏+]

标签:while   sock   his   try   .sh   flags   nec   turn   fse   

网络编程中,socket的安全关闭方法

        /// <summary>
        /// Close the socket safely.
        /// </summary>
        /// <param name="socket">The socket.</param>
        public static void SafeClose(this Socket socket)
        {
            if (socket == null)
                return;

            if (!socket.Connected)
                return;
            
            try
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            catch
            {
            }

            try
            {
                socket.Close();
            }
            catch
            {
            }
        }

        /// <summary>
        /// Sends the data.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="data">The data.</param>
        public static void SendData(this Socket client, byte[] data)
        {
            SendData(client, data, 0, data.Length);
        }

        /// <summary>
        /// Sends the data.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="data">The data.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="length">The length.</param>
        public static void SendData(this Socket client, byte[] data, int offset, int length)
        {
            int sent = 0;
            int thisSent = 0;

            while ((length - sent) > 0)
            {
                thisSent = client.Send(data, offset + sent, length - sent, SocketFlags.None);
                sent += thisSent;
            }
        }

 

C# Socket的安全关闭

标签:while   sock   his   try   .sh   flags   nec   turn   fse   

原文地址:https://www.cnblogs.com/hnsongbiao/p/8722908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!