日期:2014-05-17  浏览次数:20897 次

Socket 异步接收 缓冲区发生改变
采用异步发送和接收的方式。
发送代码

         public void ASend(string Name,byte[] Content,int size)
        {
            if (mSocket == null)
                throw new ArgumentNullException("连接不存在");
            if (Content == null)
                return;
            MyTreaty my = new MyTreaty(Name, Content,size);
            byte[] SendData = my.GetBytes();
            try
            {
               //先得到数据包的长度
               int len = SendData.Length;
               //把数据包的长度写入byte数组中
               byte[] head = BitConverter.GetBytes(len);
               byte[] newByte = new byte[head.Length + len];
               Array.Copy(head, 0, newByte, 0, head.Length);
               Array.Copy(SendData, 0, newByte, 4, len);
               mSocket.BeginSend(newByte, 0, newByte.Length, 0, new AsyncCallback(SendCallBack), mSocket);
            }
            catch(Exception ex)
            { 
            }     
        }

接收代码
        private void ReceiveCallback(IAsyncResult ar)
        {
           try
           {
              //
              StateObject state = ar.AsyncState as StateObject;
              //读取数据
              int bytesRead = mSocket.EndReceive(ar);
              if (bytesRead > 0)
              {
     &nbs