Exemplo n.º 1
0
        /// <summary>
        /// Writes the packets to the stream.
        /// </summary>
        private void WriteSubWork()
        {
            lock (sendPackets)
            {
                while (sendPackets.Count > 0)
                {
                    Packet packet = null;
                    if (!sendPackets.TryDequeue(out packet))
                    {
                        continue;
                    }

                    //Prepare some data in the packet.
                    packet.BeforeSend();

                    /*              Packet structure:
                     *              1. [16bits] packet type
                     *              2. [32bits] packet length
                     *              3. [xxbits] packet data                 */

                    byte[] packetData   = packet.GetBytes();
                    byte[] packetLength = BitConverter.GetBytes(packetData.Length);
                    byte[] packetByte   = new byte[2 + packetLength.Length + packetData.Length];

                    packetByte[0] = (byte)(typeByte[packet.GetType()]);
                    packetByte[1] = (byte)(typeByte[packet.GetType()] >> 8);
                    Array.Copy(packetLength, 0, packetByte, 2, packetLength.Length);
                    Array.Copy(packetData, 0, packetByte, 2 + packetLength.Length, packetData.Length);
                    WriteBytes(packetByte);
                }

                if (KeepAlive && nextPingStopWatch.ElapsedMilliseconds >= PING_INTERVALL)
                {
                    nextPingStopWatch.Reset();
                    currentPingStopWatch.Restart();
                    Send(new PingRequest());
                }
                else if (currentPingStopWatch.ElapsedMilliseconds >= Timeout)
                {
                    ConfigPing(KeepAlive);
                    currentPingStopWatch.Reset();
                    CloseHandler(CloseReason.Timeout);
                }
            }
        }