示例#1
0
 private void ReceiveMessage(IAsyncResult ar)
 {
     try
     {
         var client = ar.AsyncState as Socket;
         var length = client.EndReceive(ar);
         //读取出来消息内容
         int index = 0;
         if (tempBuffer != null)
         {
             int len = tempBuffer.Length - tempLen;
             if (index + len <= length)
             {
                 Array.Copy(buffer, index, tempBuffer, tempLen, len);
                 index += tempBuffer.Length - tempLen;
                 if (mSocketServer != null)
                 {
                     mSocketServer.Receive(tempBuffer);
                 }
                 tempBuffer = null;
             }
             else
             {
                 len = length;
                 Array.Copy(buffer, index, tempBuffer, tempLen, len);
                 index   += len;
                 tempLen += len;
             }
         }
         while (index < length)
         {
             byte[] lenbytes = new byte[4];
             Array.Copy(buffer, index, lenbytes, 0, 4);
             int len = System.BitConverter.ToInt32(lenbytes, 0);
             index += 4;
             //显示消息
             byte[] bytes = new byte[len];
             if (index + len <= length)
             {
                 Array.Copy(buffer, index, bytes, 0, len);
             }
             else
             {
                 tempLen = length - index;
                 Array.Copy(buffer, index, bytes, 0, tempLen);
                 tempBuffer = bytes;
                 break;
             }
             if (mSocketServer != null)
             {
                 mSocketServer.Receive(bytes);
             }
             index += len;
         }
         client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
     }
     catch (Exception ex)
     {
         Debug.LogError(ex.ToString());
     }
 }