Пример #1
0
    public void SendPack <T>(uint type, T content, MsgID msg_id) where T : ProtoBuf.IExtensible
    {
        //if (msg_id != MsgID.CheckFrameID)
        //    Logger.Log("SendPack, Msg:" + msg_id);
        //lock(m_stream)
        {
            if (m_type != Type.eVirtualServer)
            {
                if (m_client == null)
                {
                    return;
                }
                if (!m_client.Connected)
                {
                    Logger.LogWarning("SendPack, Msg:" + msg_id + " The connection is closed.");
                    return;
                }
            }
            else
            {
                if (m_stream == null)
                {
                    Logger.Log("virtual client stream is null");
                    return;
                }
            }

            try
            {
                long packTime = System.DateTime.Now.Ticks;
                using (MemoryStream msgBodyStream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize <T>(msgBodyStream, content);

                    msgBodyStream.Seek(0, SeekOrigin.Begin);

                    Pack header = new Pack();
                    header.Type      = type;
                    header.MessageID = (uint)msg_id;
                    header.AccountID = GameSystem.Instance.AccountID;
                    header.Length    = (uint)msgBodyStream.Length;

                    byte[] bodyByteArray = new byte[msgBodyStream.Length];
                    msgBodyStream.Read(bodyByteArray, 0, bodyByteArray.Length);        // 设置当前流的位置为流的开始
                    header.buffer = bodyByteArray;
                    encrypt(header);

                    byte[] msgByteArray = new byte[16 + (int)msgBodyStream.Length];
                    Array.Copy(header.AssemblyHeader(), 0, msgByteArray, 0, 16);
                    Array.Copy(bodyByteArray, 0, msgByteArray, 16, (int)msgBodyStream.Length);

                    if (!m_stream.CanWrite)
                    {
                        Logger.Log("SendPack, Msg:" + msg_id + " stream write failed.");
                        return;
                    }
                    if (m_type == Type.eVirtualServer)
                    {
                        m_stream.Seek(0, SeekOrigin.End);
                    }

                    m_stream.BeginWrite(msgByteArray, 0, msgByteArray.Length, new AsyncCallback(TCPSendCallBack), System.DateTime.Now.Ticks);
                    m_stream.Flush();
                    //Logger.Log("Write and flush-------");
                }
            }
            catch (Exception e)
            {
                if (m_type == Type.eVirtualServer)
                {
                    m_stream.Seek(0, SeekOrigin.Begin);
                    m_stream.SetLength(0);
                }
                Logger.LogError(m_type + " NetworkConn.SendPack, Msg:" + msg_id + " Error: " + e.Message);
            }
        }
    }