Esempio n. 1
0
        /// <summary>
        /// 每帧调用, 发送数据。
        /// 并包处理
        /// </summary>
        private void DoSend()
        {
            lock (m_tcpClientLocker)
            {
                if ((m_socket == null) || (m_socket.Connected == false))
                {
                    return;
                }
            }
            int nTotalLength = 0;

            // 并包
            lock (m_sendQueueLocker)
            {
                if (m_sendQueue.Count == 0)
                {
                    return;
                }
                while ((nTotalLength < MAX_BUFFER_SIZE) && m_sendQueue.Count > 0)
                {
                    byte[] packet = m_sendQueue.Peek();
                    if (nTotalLength + RESERVE_SIZE + packet.Length < MAX_BUFFER_SIZE)
                    {
                        byte[] length = m_headLengthConverter.Encode((uint)(packet.Length + RESERVE_SIZE + m_headLengthConverter.VTypeLength));
                        length.CopyTo(m_sendBuffer, nTotalLength);
                        nTotalLength += length.Length;
                        nTotalLength += RESERVE_SIZE;
                        packet.CopyTo(m_sendBuffer, nTotalLength);
                        nTotalLength += packet.Length;
                        m_sendQueue.Dequeue();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            // 真正发包到服务器
            try
            {
                m_socket.Send(m_sendBuffer, 0, nTotalLength, SocketFlags.None);
                // 清空发送缓存
                System.Array.Clear(m_sendBuffer, 0, MAX_BUFFER_SIZE);
            }
            catch (Exception e)
            {
                //LoggerHelper.Debug("stream write error : " + e.ToString());
                Debug.LogError("stream write error : " + e.ToString());
            }
        }