zoukankan      html  css  js  c++  java
  • 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();
        }
  • 相关阅读:
    bzoj 3171 [Tjoi2013]循环格(MCMF)
    spoj 839 Optimal Marks(二进制位,最小割)
    bzoj 1458 士兵占领(最大流)
    bzoj 3931 [CQOI2015]网络吞吐量(最短路,最大流)
    bzoj 2229 [Zjoi2011]最小割(分治+最小割)
    bzoj 1324 Exca王者之剑(黑白染色,最小割)
    BestCoder Round #75 解题报告
    (转)php 根据url自动生成缩略图并处理高并发问题
    PHP生成图片太慢了。。有些都不出来、
    PHP加Nginx实现动态裁剪图片方案
  • 原文地址:https://www.cnblogs.com/gzbnet/p/3194649.html
Copyright © 2011-2022 走看看