socket异步接收信息

 

  以前做过的异步接收信息,采用socket通信。

  首先建立连接,绑定端口、开始监听,然后异步接收数据,最后处理数据。

  private static List<byte[]> _listData = new List<byte[]>();
      
  public static string callBack = "";
      
  public static List<byte[]> listData { get { return _listData; } set { _listData = value; } }
       
static object LockClientSocket = new object();       
       
static Socket clientSocket;
    
  static Thread Receivethread = null; //数据接收线程
      
  static Thread DataProthread = null; //数据处理线程       
      
  public static ManualResetEvent allDone = new ManualResetEvent(false); //连接的信号

///
<summary> /// 开启接收进程 /// </summary> public static void Start() { //加一个线程来处理收到的数据 if (DataProthread == null) { DataProthread = new Thread(new ThreadStart(AlarmDataPro.DataPro)); DataProthread.IsBackground = true; DataProthread.Start(); } if (Receivethread == null) { Receivethread = new Thread(new ThreadStart(DataReceiveProc)); Receivethread.IsBackground = true; Receivethread.Start(); } } /// <summary> /// 停止接收进程 /// </summary> public static void Stop() { try { if (DataProthread != null) { DataProthread.Abort(); DataProthread = null; } if (Receivethread != null) { if (clientSocket != null) { clientSocket.Close(); clientSocket = null; } Receivethread.Abort(); Receivethread = null; } } catch (Exception ex) { AlarmDataPro.WriteErrLog("ReceiveMethod.Stop", ex); } }

 


   一般使用时是开启一个线程来开启接收服务,在开一个线程来处理数据,结束线程也是一样。

/// <summary>
        /// 接收网关发来的数据
        /// </summary>
        public static void DataReceiveProc()
        {
            try
            {
                int port = 14000;//端口14000
                IPEndPoint ipe = new IPEndPoint(IPAddress.Any, port);
                if (clientSocket == null)
                {
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                }
                clientSocket.Bind(ipe);//绑定14000端口
                clientSocket.Listen(100);//开始监听
                IPEndPoint _sender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint senderRemote = (EndPoint)_sender;
                while (true)
                {
                    try
                    {
                        allDone.Reset();
                        clientSocket.BeginAccept(new AsyncCallback(AcceptCallback), clientSocket);
                        allDone.WaitOne();
                    }
                    catch (ThreadAbortException ex0)
                    {
                        AlarmDataPro.WriteErrLog("ReceiveMethod接收数据ThreadAbortException", ex0);
                    }
                    catch (Exception e)
                    {
                        AlarmDataPro.WriteErrLog("ReceiveMethod接收数据", e);
                    }
                }
            }
            catch (Exception e)
            {
                AlarmDataPro.WriteErrLog("ReceiveMethod.DataReceiveProc()", e);
            }
        }
/// <summary>
        /// BeginAccept的异步回调函数
        /// </summary>
        /// <param name="ar"></param>
        public static void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                //添加此命令,让主线程继续.
                allDone.Set();
                // 获取客户请求的socket
                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);
                byte[] recvBytes = new byte[1024];
                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadCallback), state);
            }
            catch (Exception e)
            {            
    AlarmDataPro.WriteErrLog ("ReceiveMethod.AcceptCallback.EndAccept()", e);
            }
        }
/// <summary>
        /// BeginReceive的异步回调函数
        /// </summary>
        /// <param name="ar"></param>
        public static void ReadCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;
                // 从异步state对象中获取state和socket对象.
                StateObject state = (StateObject)ar.AsyncState;
                Socket handler = state.workSocket;
                // 从客户socket读取数据. 
                int len = handler.EndReceive(ar);
                if (len > 0)
                {
                    //所有数据读取完毕.
                    lock (listData)
                    {
                        byte[] data_bak = new byte[1024];
                        Array.Copy(state.buffer.Take(len).ToArray(), data_bak, len);
                        listData.Add(data_bak);
                    }
                }
                else
                {
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                AlarmDataPro.WriteErrLog("ReceiveMethod.ReadCallback.EndReceive()", e);
            }
        }
/// <summary>
    /// 封装一个类,(异步接收用到)
    /// </summary>
    public class StateObject
    {
        // Client  socket.    
        public Socket workSocket = null;
        // Size of receive buffer.    
        public const int BufferSize = 1024;
        // Receive buffer.    
        public byte[] buffer = new byte[BufferSize];
        // Received data string.    
        public StringBuilder sb = new StringBuilder();
    }

 

 

 

posted @ 2013-07-16 23:37  戒一字  阅读(735)  评论(0编辑  收藏  举报