zoukankan      html  css  js  c++  java
  • C# Socket的安全关闭

    网络编程中,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;
                }
            }
  • 相关阅读:
    第二阶段冲刺第七天
    学习进度表_十五周
    第二阶段冲刺第六天
    第二阶段冲刺第五天
    第二阶段冲刺第四天
    第二阶段冲刺第三天
    Beta阶段项目总结
    Alpha阶段项目总结
    第二次冲刺站立会议10
    第二次冲刺站立会议09
  • 原文地址:https://www.cnblogs.com/hnsongbiao/p/8722908.html
Copyright © 2011-2022 走看看