www.pudn.com > sharewindows.rar > Nblh_Link_Service.cs, change:2016-01-07,size:9292b


using NBLH_LINK.Args; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
 
namespace NBLH_LINK 
{ 
    public delegate void ServerReceiveHandle(object sender, Nblh_Args_Buffer buffer); 
    public class Nblh_Link_Service:Nblh_Link_Base 
    { 
        // 接收客户端事件 
        public event ServerReceiveHandle ReceiveEvent; 
 
        ManualResetEvent m_receiveDone = new ManualResetEvent(false); 
        ManualResetEvent m_acceptDone = new ManualResetEvent(false); 
 
        IList<Socket> m_clients = new List<Socket>(); 
 
        public Nblh_Link_Service() 
        { 
            StatusType = STATUS_TYPE.STOP; 
        } 
        ~Nblh_Link_Service() 
        { 
            StatusType = STATUS_TYPE.STOP; 
        } 
        public override void Func_Link_Init(IPAddress ipaddress, int port) 
        { 
            base.Func_Link_Init(ipaddress, port); 
 
            Func_Link_Init(port); 
        } 
        public override void Func_Link_Init(string ip, int port) 
        { 
            base.Func_Link_Init(ip, port); 
            Func_Link_Init(IPAddress.Parse(ip), port); 
        } 
        /// <summary> 
        /// 初始化连接 
        /// </summary> 
        /// <param name="port"></param> 
        public override void Func_Link_Init(int port) 
        { 
            try 
            { 
                if(StatusType == STATUS_TYPE.START|| StatusType== STATUS_TYPE.PAUSE) 
                { 
                    return; 
                } 
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                // duan 
                m_socket.ExclusiveAddressUse = false; 
                m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 
                IPEndPoint epoint = new IPEndPoint(IPAddress.Any, port); 
                m_socket.Bind(epoint); 
                m_socket.Listen(100); 
                   
                StatusType = STATUS_TYPE.START; 
                SendMessage(Nblh_Link_Resource.STRING_SERVER_LINK_SUCCESS); 
 
                ThreadPool.QueueUserWorkItem(m => { Func_Link_Run_Accept(); }); 
            } 
            catch (ArgumentNullException ex) 
            { 
                SendMessage(ex.Message); 
            } 
            catch (FormatException ex) 
            { 
                SendMessage(ex.Message); 
            } 
            catch (SocketException ex) 
            { 
                SendMessage(ex.Message); 
            } 
            catch (ObjectDisposedException ex) 
            { 
                SendMessage(ex.Message); 
            } 
            catch (Exception ex) 
            { 
                SendMessage(ex.Message); 
            }             
        } 
        public void Func_Link_Run_Accept() 
        { 
            while(true) 
            { 
                if (StatusType == STATUS_TYPE.STOP || StatusType == STATUS_TYPE.NONE) 
                { 
                    return; 
                } 
                while(StatusType== STATUS_TYPE.PAUSE) 
                { 
                    Thread.Sleep(1000); 
                } 
                try 
                { 
                    // 开始监听 
                    Socket client = m_socket.Accept(); 
                    // 创建链接 
                    SendMessage(string.Format(Nblh_Link_Resource.STRING_SERVER_CLIENT_ACCEPTED,client.RemoteEndPoint.ToString())); 
                    m_clients.Add(client); 
                    ThreadPool.QueueUserWorkItem(n => { Func_Link_Receive(client); }); 
                }    
                catch(SocketException ex) 
                { 
 
                } 
                catch(Exception ex) 
                { 
 
                } 
            } 
        } 
        public override void Func_Link_Free() 
        { 
            try 
            { 
                base.Func_Link_Free(); 
                this.StatusType = STATUS_TYPE.STOP; 
                //关闭所有客户端并清空客户端列表集合 
                m_clients.ToList().ForEach(o => o.Close()); 
                m_clients.Clear(); 
                // 停止服务端套接字 
                m_socket.Close(); 
                 
            } 
            catch(SocketException ex) 
            { 
                SendMessage(ex.Message); 
            } 
            catch(Exception ex) 
            { 
                SendMessage(ex.Message); 
            } 
             
        } 
        /// <summary> 
        /// 接收客户端数据 
        /// </summary> 
        /// <param name="result"></param> 
        private void Func_Link_Receive(Socket client) 
        { 
            try 
            { 
                Buffer buffer=new Buffer(); 
                if (client.Connected == false) 
                { 
                    Func_Link_Deal_DisConnect(client, Nblh_Link_Resource.STRING_SERVER_CLINET_LOST); 
                } 
                while(true) 
                { 
                    int len = 0; 
                    byte[] bytes = new byte[sizeof(int)]; 
                    len = client.Receive(bytes, sizeof(int), SocketFlags.None); 
                    if (len <= 0) 
                    { 
                        Func_Link_Deal_DisConnect(client, Nblh_Link_Resource.STRING_SERVER_CLINET_LOST); 
                        return; 
                    } 
                    buffer.length = BitConverter.ToInt32(bytes, 0); 
                    buffer.buffer = new byte[buffer.length]; 
 
 
                    int recvLen = 0; 
                    while (recvLen < buffer.length) 
                    { 
                        len = client.Receive(buffer.buffer, recvLen, buffer.length - recvLen, SocketFlags.None); 
                        if (len <= 0) 
                        { 
                            Func_Link_Deal_DisConnect(client, Nblh_Link_Resource.STRING_SERVER_CLINET_LOST); 
                            return; 
                        } 
                        recvLen += len; 
                    } 
                    SendMessage(string.Format(Nblh_Link_Resource.STRING_SERVER_CLINET_RECEIVED, client.RemoteEndPoint.ToString(), recvLen)); 
                    if (len <= 0) 
                    { 
                        Func_Link_Deal_DisConnect(client, Nblh_Link_Resource.STRING_SERVER_CLINET_LOST); 
                        return; 
                    } 
                    if (ReceiveEvent!=null) 
                    { 
                        ReceiveEvent(client, new Nblh_Args_Buffer(buffer.buffer, 0, buffer.length)); 
                    } 
                } 
            } 
            catch (SocketException ex) 
            { 
 
                Func_Link_Deal_DisConnect(client, ex.Message); 
            } 
            catch (Exception ex) 
            { 
                Func_Link_Deal_DisConnect(client, ex.Message); 
            } 
            finally 
            { 
               // Monitor.Exit(this); 
            } 
        } 
        /// <summary> 
        /// 发送客户端数据 
        /// </summary> 
        /// <param name="result"></param> 
        public void Func_Link_Send(Socket client, byte[] bytes, int index, int length) 
        { 
            try 
            { 
                int size = 0; 
                //  
                size = client.Send(BitConverter.GetBytes(length), sizeof(int), SocketFlags.None); 
                if (size <= 0) 
                { 
                    Func_Link_Deal_DisConnect(client, Nblh_Link_Resource.STRING_SERVER_CLINET_LOST); 
                } 
                int sendIndex = index; 
                int endIndex = index + length; 
                while (sendIndex < endIndex) 
                { 
                    size = client.Send(bytes, sendIndex, endIndex - sendIndex, SocketFlags.None); 
                    if (size <= 0) 
                    { 
                        // 可能通讯断开 
                    } 
                    sendIndex += size; 
                } 
            } 
            catch (SocketException ex) 
            { 
                Func_Link_Deal_DisConnect(client, ex.Message); 
            } 
            catch (Exception ex) 
            { 
                Func_Link_Deal_DisConnect(client, ex.Message); 
            } 
        } 
        /// <summary> 
        /// 处理断开连接套接字 
        /// </summary> 
        /// <param name="result"></param> 
        /// <param name="message"></param> 
        protected virtual void Func_Link_Deal_DisConnect(Socket client, string message) 
        { 
            try 
            { 
                for(int pos=this.m_clients.Count-1;pos>=0;pos++) 
                { 
                    if (m_clients[pos].Equals(client) == true) 
                    { 
                        m_clients[pos].Close(); 
                        SendMessage(string.Format(Nblh_Link_Resource.STRING_SERVER_CLINET_LOST)); 
                        this.m_clients.RemoveAt(pos); 
                    } 
                } 
            } 
            catch(Exception ex) 
            { 
 
            } 
 
        } 
        
    } 
}