Exemplo n.º 1
0
 public void FlushPackets()
 {
     while (PacketQueue.Count > 0)
     {
         IStarboundPacket next;
         while (!PacketQueue.TryDequeue(out next))
         {
             ;
         }
         var memoryStream = new MemoryStream();
         var stream       = new StarboundStream(memoryStream);
         next.Write(stream);
         byte[] buffer = new byte[stream.Position];
         Array.Copy(memoryStream.GetBuffer(), buffer, buffer.Length);
         int length     = buffer.Length;
         var compressed = ZlibStream.CompressBuffer(buffer);
         if (compressed.Length < buffer.Length)
         {
             buffer = compressed;
             length = -buffer.Length;
         }
         byte[] header = new byte[StarboundStream.GetSignedVLQLength(length) + 1];
         header[0] = next.PacketId;
         int discarded;
         StarboundStream.WriteSignedVLQ(header, 1, length, out discarded);
         int payloadStart = header.Length;
         Array.Resize(ref header, header.Length + buffer.Length);
         Array.Copy(buffer, 0, header, payloadStart, buffer.Length);
         lock (PacketsWaitingLock)
             PacketsWaiting++;
         EmptyQueueReset.Reset();
         Socket.BeginSend(header, 0, header.Length, SocketFlags.None, r =>
         {
             lock (PacketsWaitingLock)
             {
                 PacketsWaiting--;
                 if (PacketsWaiting == 0)
                 {
                     EmptyQueueReset.Set();
                 }
             }
         }, null);
     }
 }