Socket 스티커 처리

1512 단어
/// 
    ///      
    /// 
    void OnReceive(byte[] bytes, int length)
    {
        //         ,   memStream   
        memStream.Seek(0, SeekOrigin.End);
        memStream.Write(bytes, 0, length);
        //    menStreamd    
        memStream.Seek(0, SeekOrigin.Begin);

        //int32  4   ,ushort  2   
        int lengthCount = 4;
        while (RemainingBytes() > lengthCount)
        {
            //    4     :        
            int messageLen = reader.ReadInt32();
            if (RemainingBytes() >= messageLen)
            {
                MemoryStream ms = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(ms);
                //                     ,              
                writer.Write(reader.ReadBytes(messageLen));
                ms.Seek(0, SeekOrigin.Begin);

                //     memStream ,     
                OnReceivedMessage(ms);
            }else{
                //       ,      int ,    ,      
                memStream.Position = memStream.Position - lengthCount;
                break;
            }
        }

        //Create a new stream with any leftover bytes
        byte[] leftover = reader.ReadBytes((int)RemainingBytes());
        memStream.SetLength(0);     //Clear
        memStream.Write(leftover, 0, leftover.Length);
    }

    /// 
    ///      
    /// 
    private long RemainingBytes()
    {
        return memStream.Length - memStream.Position;
    }

좋은 웹페이지 즐겨찾기