Пример #1
0
        void ReceiveCallback(IAsyncResult ar)
        {
            SocketTool frd = (SocketTool)ar.AsyncState;

            try
            {
                int i = frd.socket.EndReceive(ar);
                if (i == 0)
                {
                    return;
                }
                else
                {
                    string data = System.Text.Encoding.UTF8.GetString(frd.Rcvbuffer, 0, i);
                    try
                    {
                        Log.Output(data);
                        LisDataAnalysis(data);
                    }
                    catch { }
                    frd.ClearBuffer();
                    frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), frd);
                }
            }
            catch (Exception ex)
            {
                this.SetSocketInfo(ex.Message);
                Log.Output(ex.Message);
            }
        }
Пример #2
0
 void AcceptCallback(IAsyncResult ar)
 {
     try
     {
         //完成异步接受连接请求的异步调用
         //将连接信息添加到列表和下拉列表框中
         Socket     handle = listener.EndAcceptSocket(ar);
         SocketTool frd    = new SocketTool(handle);
         //继续调用异步方法接收连接请求
         if (isListenStart)
         {
             listener.BeginAcceptSocket(new AsyncCallback(AcceptCallback), listener);
         }
         //开始在连接上进行异步的数据接收
         frd.ClearBuffer();
         frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), frd);
     }
     catch (Exception ex)
     {
         //在调用EndAcceptSocket方法时可能引发异常
         //——套接字Listener被关闭,则设置为未启动侦听状态
         isListenStart = false;
         this.SetSocketInfo(ex.Message);
     }
 }