Beispiel #1
0
    /*登录 */
    public void LogIn()
    {
        if (isInLogIn || isInRegister)
        {
            return;                             //若已点击了登陆按钮或注册按钮则不响应
        }
        StopCoroutine("ResetPrompt");
        promptText.text = "";

        userNameInput.interactable = false;
        passwordInput.interactable = false;
        isInLogIn = true;
        //test
        // LogInSuccess();
        ByteBuilder builder = new ByteBuilder();

        builder.Add(System.BitConverter.GetBytes(Network.LOGIN));
        builder.Add(System.BitConverter.GetBytes(userNameInput.text.Length));
        builder.Add(System.BitConverter.GetBytes(passwordInput.text.Length));
        builder.Add(System.Text.Encoding.ASCII.GetBytes(userNameInput.text));
        builder.Add(System.Text.Encoding.ASCII.GetBytes(passwordInput.text));
        Global.network.Send(builder.GetByes());
        // Debug.Log("Set");
        LogInOutCor = StartCoroutine(LogInTimeout());
    }
Beispiel #2
0
        private void sendMsg(long peerId, IExtensible msg)
        {
            var frame   = PBSerializer.Serialize(msg);
            var builder = new ByteBuilder();

            builder.Add(frame.Length, Endians.Little);
            builder.Add(frame);
            svr.SendBytes(peerId, builder.ToArrayThenClear());
        }
Beispiel #3
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(30);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_MessageId)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                return(builder.ToArray());
            }
Beispiel #4
0
        public void Send(IExtensible msg)
        {
            Debug.Assert(peerId != 0);

            var frame   = PBSerializer.Serialize(msg);
            var builder = new ByteBuilder();

            builder.Add(frame.Length, Endians.Little);
            builder.Add(frame);
            cli.SendBytes(peerId, builder.ToArrayThenClear());
        }
Beispiel #5
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(90);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SystemId)));
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_Password)));
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SystemType)));
                builder.Add(_InterfaceVersion);
                builder.Add(_AddressTon);
                builder.Add(_AddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_AddressRange)));
                return(builder.ToArray());
            }
Beispiel #6
0
        void SendResponse(ClientInfo ci, HttpRequest req, HttpResponse resp, bool close)
        {
            var en = Encoding.Default;

#if DEBUG
            Console.WriteLine("Response: " + resp.ReturnCode + Responses[resp.ReturnCode]);
#endif
            ByteBuilder bb = new ByteBuilder();
            bb.Add(en.GetBytes("HTTP/1.1 " + resp.ReturnCode + " " + Responses[resp.ReturnCode] +
                               "\r\nDate: " + DateTime.Now.ToString("R") +
                               "\r\nServer: RedCoronaEmbedded/1.0" +
                               "\r\nConnection: " + (close ? "close" : "Keep-Alive")));
            if (resp.RawContent == null)
            {
                //bb.Add(Encoding.UTF8.GetBytes("\r\nContent-Encoding: utf-8" +
                //    "\r\nContent-Length: " + resp.Content.Length));

                bb.Add(en.GetBytes("\r\nContent-Encoding: " + en.BodyName + "" +
                                   "\r\nContent-Length: " + (en.GetByteCount(resp.Content))));
            }
            else
            {
                bb.Add(en.GetBytes("\r\nContent-Length: " + resp.RawContent.Length));
            }
            if (resp.ContentType != null)
            {
                bb.Add(en.GetBytes("\r\nContent-Type: " + resp.ContentType));
            }
            if (req.Session != null)
            {
                bb.Add(en.GetBytes("\r\nSet-Cookie: _sessid=" + req.Session.ID + "; path=/"));
            }
            foreach (KeyValuePair <string, string> de in resp.Header)
            {
                //bb.Add(Encoding.UTF8.GetBytes("\r\n" + de.Key + ": " + de.Value));
                bb.Add(en.GetBytes("\r\n" + de.Key + ": " + de.Value));
            }
            bb.Add(en.GetBytes("\r\n\r\n")); // End of header
            if (resp.RawContent != null)
            {
                bb.Add(resp.RawContent);
            }
            else
            {
                //bb.Add(Encoding.UTF8.GetBytes(resp.Content));
                bb.Add(en.GetBytes(resp.Content));
            }
            ci.Send(bb.Read(0, bb.Length));
#if DEBUG
            Console.WriteLine("** SENDING\n" + resp.Content);
#endif
            if (close)
            {
                ci.Close();
            }
        }
Beispiel #7
0
        /// <summary>
        /// 转换为二进制数据
        /// </summary>
        /// <returns></returns>
        public override byte[] ToByteArray()
        {
            // 总长度(4) + command(4) + hashCode(4)
            const int headLength = 12;
            // 总长度
            int totalLength = this.Body == null ? headLength : headLength + this.Body.Length;

            var builder = new ByteBuilder(totalLength);

            builder.Add(totalLength, Endians.Big);
            builder.Add(this.Command, Endians.Big);
            builder.Add(this.HashCode, Endians.Big);
            builder.Add(this.Body);
            return(builder.Source);
        }
Beispiel #8
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(30);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_MessageId)));
                if (_FinalDate == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_FinalDate.SmppDate)));
                }
                builder.Add(_MessageState);
                builder.Add(_ErrorCode);
                return(builder.ToArray());
            }
Beispiel #9
0
        /// <summary>
        /// 转换为ByteRange
        /// </summary>
        /// <exception cref="ProtocolException"></exception>
        /// <returns></returns>
        public ByteRange ToByteRange()
        {
            var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName);
            var headLength   = apiNameBytes.Length + 15;

            this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length;

            const int packegMaxSize = 10 * 1204 * 1024; // 10M

            if (this.TotalBytes > packegMaxSize)
            {
                throw new ProtocolException("数据包太大");
            }

            this.ApiNameLength = (byte)apiNameBytes.Length;
            var builder = new ByteBuilder(Endians.Big);

            builder.Add(this.TotalBytes);
            builder.Add(this.ApiNameLength);
            builder.Add(apiNameBytes);
            builder.Add(this.Id);
            builder.Add(this.IsFromClient);
            builder.Add(this.IsException);
            builder.Add(this.Body);
            return(builder.ToByteRange());
        }
Beispiel #10
0
        /// <summary>
        /// 输出文本内容
        /// </summary>
        /// <param name="content">内容</param>
        public bool Write(string content)
        {
            if (content == null)
            {
                content = string.Empty;
            }
            var buffer       = new ByteBuilder(Endians.Little);
            var contentBytes = this.Charset.GetBytes(content);

            if (this.wroteHeader == false)
            {
                this.wroteHeader = true;
                var headerByes = this.GetHeaderBytes(contentBytes.Length);
                buffer.Add(headerByes);
            }

            buffer.Add(contentBytes);
            return(this.TrySend(buffer.ToByteRange()));
        }
Beispiel #11
0
        /// <summary>
        /// 将参数序列化并写入为Body
        /// </summary>
        /// <param name="serializer">序列化工具</param>
        /// <param name="parameters">参数</param>
        /// <exception cref="SerializerException"></exception>
        public void SetBodyParameters(ISerializer serializer, params object[] parameters)
        {
            if (parameters == null || parameters.Length == 0)
            {
                return;
            }
            var builder = new ByteBuilder(Endians.Big);

            foreach (var item in parameters)
            {
                // 序列化参数为二进制内容
                var paramBytes = serializer.Serialize(item);
                // 添加参数内容长度
                builder.Add(paramBytes == null ? 0 : paramBytes.Length);
                // 添加参数内容
                builder.Add(paramBytes);
            }
            this.Body = builder.ToArray();
        }
Beispiel #12
0
        public void Send(string msg)
        {
            if (peerId == 0)
            {
                this.Warn("not conect yet");
                return;
            }

            var frame   = Encoding.ASCII.GetBytes(msg);
            var builder = new ByteBuilder();

            builder.Add(frame);
            cli.SendBytes(peerId, builder.ToArrayThenClear());
        }
Beispiel #13
0
    /*结束游戏 */
    public void OverGame()
    {
        Debug.Log("OVer");
        isDead = true;
        promptText.gameObject.SetActive(true);
        promptText.text = "同步中";
        int score = int.Parse(scoreText.text);

        Global.killSum += score;
        if (aliveTime > Global.maxAliveTime)
        {
            Global.maxAliveTime = aliveTime;
        }
        ByteBuilder builder = new ByteBuilder();

        builder.Add(System.BitConverter.GetBytes(Network.MATCH_INFO));
        builder.Add(System.BitConverter.GetBytes(Global.killSum));
        builder.Add(System.BitConverter.GetBytes((double)aliveTime));   //double
        builder.Add(System.BitConverter.GetBytes(Global.userName.Length));
        builder.Add(System.Text.Encoding.ASCII.GetBytes(Global.userName));
        Global.network.Send(builder.GetByes());
        StartCoroutine(TimeOut());
    }
        /// <summary>
        /// 输出内容块
        /// </summary>
        /// <param name="buffer">内容</param>
        /// <param name="offset">偏移量</param>
        /// <param name="count">长度</param>
        /// <returns></returns>
        private bool WirteChunked(byte[] buffer, int offset, int count)
        {
            if (this.writeEnd == true)
            {
                return(false);
            }

            var builder = new ByteBuilder(Endians.Big);
            var size    = Encoding.ASCII.GetBytes(Convert.ToString(count, 16));

            builder.Add(size);
            builder.Add(CRLF);
            if (buffer != null)
            {
                builder.Add(buffer, offset, count);
            }
            builder.Add(CRLF);
            if (count == 0)
            {
                builder.Add(CRLF);
            }
            return(this.response.WriteContent(builder.ToArraySegment()));
        }
Beispiel #15
0
    /*注册 */
    public void Register()
    {
        if (isInLogIn || isInRegister)
        {
            return;                             //若已点击了登陆按钮或注册按钮则不响应
        }
        userNameInput.interactable = false;
        passwordInput.interactable = false;

        StopCoroutine("ResetPrompt");
        promptText.text = "";
        isInRegister    = true;

        ByteBuilder builder = new ByteBuilder();

        builder.Add(System.BitConverter.GetBytes(Network.REGISTER));
        builder.Add(System.BitConverter.GetBytes(userNameInput.text.Length));
        builder.Add(System.BitConverter.GetBytes(passwordInput.text.Length));
        builder.Add(System.Text.Encoding.ASCII.GetBytes(userNameInput.text));
        builder.Add(System.Text.Encoding.ASCII.GetBytes(passwordInput.text));
        Global.network.Send(builder.GetByes());

        RegisterOutCor = StartCoroutine(RegisterTimeout());
    }
Beispiel #16
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(100);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ServiceType.Value)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                builder.Add(_DestinationAddressTon);
                builder.Add(_DestinationAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_DestinationAddress)));
                builder.Add(_EsmClass.Value);
                builder.Add(_RegisteredDelivery.Value);
                builder.Add(_DataCoding.Value);
                return(builder.ToArray());
            }
Beispiel #17
0
        /// <summary>
        /// 转换为ArraySegment
        /// </summary>
        /// <param name="mask">是否打码</param>
        /// <returns></returns>
        public override unsafe ArraySegment <byte> ToArraySegment(bool mask)
        {
            var builder = new ByteBuilder(Endians.Big);

            ByteBits bits = (byte)this.Frame;

            bits[0] = this.Fin;
            builder.Add(bits);

            if (this.Content.Length > UInt16.MaxValue)
            {
                builder.Add(mask ? byte.MaxValue : (byte)127);
                builder.Add((ulong)this.Content.Length);
            }
            else if (this.Content.Length > 125)
            {
                builder.Add(mask ? (byte)254 : (byte)126);
                builder.Add((ushort)this.Content.Length);
            }
            else
            {
                var len = mask ? (byte)(this.Content.Length + 128) : (byte)this.Content.Length;
                builder.Add(len);
            }

            if (mask == true)
            {
                var maskingKey = ByteConverter.ToBytes(ran.Next(), Endians.Big);
                builder.Add(maskingKey);

                fixed(byte *pcontent = &this.Content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < this.Content.Length; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            builder.Add(this.Content);
            return(builder.ToArraySegment());
        }
Beispiel #18
0
        /// <summary>
        /// 转换为ArraySegment
        /// </summary>
        /// <returns></returns>
        public ArraySegment <byte> ToArraySegment()
        {
            var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName);
            var headLength   = apiNameBytes.Length + 16;

            this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length;

            this.ApiNameLength = (byte)apiNameBytes.Length;
            var builder = new ByteBuilder(Endians.Big);

            builder.Add(FastPacket.Mark);
            builder.Add(this.TotalBytes);
            builder.Add(this.ApiNameLength);
            builder.Add(apiNameBytes);
            builder.Add(this.Id);
            builder.Add(this.IsFromClient);
            builder.Add(this.IsException);
            builder.Add(this.Body);
            return(builder.ToArraySegment());
        }
        /// <summary>
        /// 转换为ByteRange
        /// </summary>
        /// <returns></returns>
        public override ByteRange ToByteRange()
        {
            var builder = new ByteBuilder(Endians.Big);

            builder.Add((byte)((byte)this.Frame + 128));

            if (this.Content.Length > UInt16.MaxValue)
            {
                builder.Add((byte)127);
                builder.Add((ulong)this.Content.Length);
            }
            else if (this.Content.Length > 125)
            {
                builder.Add((byte)126);
                builder.Add((ushort)this.Content.Length);
            }
            else
            {
                builder.Add((byte)this.Content.Length);
            }
            builder.Add(this.Content);
            return builder.ToByteRange();
        }
Beispiel #20
0
        /// <summary>
        /// 转换为ByteRange
        /// </summary>
        /// <returns></returns>
        public override ByteRange ToByteRange()
        {
            var builder = new ByteBuilder(Endians.Big);

            builder.Add((byte)((byte)this.Frame + 128));

            if (this.Content.Length > UInt16.MaxValue)
            {
                builder.Add((byte)127);
                builder.Add((ulong)this.Content.Length);
            }
            else if (this.Content.Length > 125)
            {
                builder.Add((byte)126);
                builder.Add((ushort)this.Content.Length);
            }
            else
            {
                builder.Add((byte)this.Content.Length);
            }
            builder.Add(this.Content);
            return(builder.ToByteRange());
        }
Beispiel #21
0
        /// <summary>
        /// 将数据作帧处理
        /// </summary>
        /// <param name="bytes">原始数据</param>
        /// <param name="frameType">帧类型</param>
        /// <returns></returns>
        protected byte[] FrameBuffer(byte[] bytes, FrameTypes frameType)
        {
            var builder = new ByteBuilder();

            builder.Add((byte)((byte)frameType + 128));

            if (bytes.Length > UInt16.MaxValue)
            {
                builder.Add((byte)127);
                builder.Add((ulong)bytes.Length, Endians.Big);
            }
            else if (bytes.Length > 125)
            {
                builder.Add((byte)126);
                builder.Add((ushort)bytes.Length, Endians.Big);
            }
            else
            {
                builder.Add((byte)bytes.Length);
            }
            builder.Add(bytes);
            return(builder.ToArray());
        }
Beispiel #22
0
    // Update is called once per frame
    void Update()
    {
        //创建敌人
        if (detectors.Count != 0)
        {
            foreach (GameObject obj in detectors)
            {
                if (!obj.activeSelf)
                {
                    deletes.AddLast(obj);
                }
            }
            foreach (GameObject obj in deletes)
            {
                detectors.Remove(obj);
                GameObject.Destroy(obj);
            }
            foreach (GameObject obj in detectors)
            {
                GameObject rival = Instantiate(rivalPrefab, new Vector3(obj.transform.position.x, rivalPrefab.transform.position.y, obj.transform.position.z), Quaternion.identity);
                rival.transform.Rotate(0f, Random.Range(-180f, 180f), 0f, Space.Self);
                rivalList.AddLast(rival);

                RivalController controller = rival.GetComponent <RivalController>();
                controller.DelegateDie(new DieCallback(OnRivalDie));
                controller.id = idNext;
                ++idNext;

                GameObject.Destroy(obj);
                ++completeNum;
            }
            detectors.Clear();
            deletes.Clear();
        }

        //询问服务器是否需新创建敌人
        if (isCreateOver && createRivalNum <= 0 && isRecv)
        {
            StartCoroutine("ResetRecv");
            byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_NUM));
            byteBuilder.Add(System.BitConverter.GetBytes(rivalList.Count));
            Global.network.Send(byteBuilder.GetByes());
            byteBuilder.Clear();
            isRecv = false;
        }
        else if (!isCreateOver && requestNum == createRivalNum) //检查是否创建成功
        {
            createRivalNum = requestNum - completeNum;
            //开始将未创建成功的创建
            for (int i = 0; i < createRivalNum; ++i)
            {
                CreateDetector();
            }
            requestNum  = 0;
            completeNum = 0;
        }

        if (!isCreateOver && createRivalNum <= 0)    //检查是否全部创建完成
        {
            completeNum    = 0;
            requestNum     = 0;
            createRivalNum = 0;
            isCreateOver   = true;
        }

        if (isCreateOver && createRivalNum > 0)  //检查是否有待创建的敌人
        {
            //开始将未创建成功的创建
            for (int i = 0; i < createRivalNum; ++i)
            {
                CreateDetector();
            }
            isCreateOver = false;
            requestNum   = 0;
            completeNum  = 0;
        }
    }
Beispiel #23
0
 /// <summary>
 /// 将参数序列化并写入为Body
 /// </summary>
 /// <param name="serializer">序列化工具</param>
 /// <param name="parameters">参数</param>
 /// <exception cref="SerializerException"></exception>
 public void SetBodyParameters(ISerializer serializer, params object[] parameters)
 {
     if (parameters == null || parameters.Length == 0)
     {
         return;
     }
     var builder = new ByteBuilder(Endians.Big);
     foreach (var item in parameters)
     {
         // 序列化参数为二进制内容
         var paramBytes = serializer.Serialize(item);
         // 添加参数内容长度
         builder.Add(paramBytes == null ? 0 : paramBytes.Length);
         // 添加参数内容
         builder.Add(paramBytes);
     }
     this.Body = builder.ToArray();
 }
Beispiel #24
0
        /// <summary>
        /// 转换为ByteRange
        /// </summary>
        /// <exception cref="ProtocolException"></exception>
        /// <returns></returns>
        public ByteRange ToByteRange()
        {
            var apiNameBytes = Encoding.UTF8.GetBytes(this.ApiName);
            var headLength = apiNameBytes.Length + 15;
            this.TotalBytes = this.Body == null ? headLength : headLength + this.Body.Length;

            const int packegMaxSize = 10 * 1204 * 1024; // 10M
            if (this.TotalBytes > packegMaxSize)
            {
                throw new ProtocolException();
            }

            this.ApiNameLength = (byte)apiNameBytes.Length;
            var builder = new ByteBuilder(Endians.Big);
            builder.Add(this.TotalBytes);
            builder.Add(this.ApiNameLength);
            builder.Add(apiNameBytes);
            builder.Add(this.Id);
            builder.Add(this.IsFromClient);
            builder.Add(this.IsException);
            builder.Add(this.Body);
            return builder.ToByteRange();
        }
        /// <summary>
        /// 输出文本内容
        /// </summary>      
        /// <param name="content">内容</param>
        public bool Write(string content)
        {
            if (content == null)
            {
                content = string.Empty;
            }
            var buffer = new ByteBuilder(Endians.Little);
            var contentBytes = this.Charset.GetBytes(content);

            if (this.wroteHeader == false)
            {
                this.wroteHeader = true;
                var headerByes = this.GetHeaderBytes(contentBytes.Length);
                buffer.Add(headerByes);
            }

            buffer.Add(contentBytes);
            return this.TrySend(buffer.ToByteRange());
        }
Beispiel #26
0
            public byte[] ToByteArray()
            {
                var builder = new ByteBuilder(300);

                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ServiceType.Value)));
                builder.Add(_SourceAddressTon);
                builder.Add(_SourceAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_SourceAddress)));
                builder.Add(_DestinationAddressTon);
                builder.Add(_DestinationAddressNpi);
                builder.AddRange(SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_DestinationAddress)));
                builder.Add(_EsmClass.Value);
                builder.Add(_ProtocolId);
                builder.Add(_PriorityFlag);
                if (_ScheduleDeliveryTime == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(
                        SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ScheduleDeliveryTime.SmppDate)));
                }
                if (_ValidityPeriod == null)
                {
                    builder.AddRange(SmppConverter.SmppNullEnd(null));
                }
                else
                {
                    builder.AddRange(
                        SmppConverter.SmppNullEnd(SmppDataCoding.BaseEncoding.GetBytes(_ValidityPeriod.SmppDate)));
                }
                builder.Add(_RegisteredDelivery.Value);
                builder.Add(_ReplaceIfPresent);
                builder.Add(_ShortMessage.DataCoding.Value);
                builder.Add(_SmDefaultMessageId);
                builder.Add(Convert.ToByte(_ShortMessage.Length));
                builder.AddRange(_ShortMessage.Value);
                return(builder.ToArray());
            }
Beispiel #27
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="builder">所有收到的数据</param>
        /// <param name="resultBuilder">用于保存数理后的数据</param>
        /// <returns></returns>
        public unsafe static Hybi13Packet GetPacket(ByteBuilder builder, ByteBuilder resultBuilder)
        {
            if (builder.Length < 2)
            {
                return(null);
            }

            var isFinal      = (builder.ToByte(0) & 128) != 0;
            var reservedBits = builder.ToByte(0) & 112;
            var frameType    = (FrameTypes)(builder.ToByte(0) & 15);
            var isMasked     = (builder.ToByte(1) & 128) != 0;
            var length       = builder.ToByte(1) & 127;

            if (isMasked == false || Enum.IsDefined(typeof(FrameTypes), frameType) == false || reservedBits != 0)
            {
                return(null);
            }

            // 计算数据长度和mask索引
            var maskIndex = 2;

            if (length == 127)
            {
                if (builder.Length < maskIndex + 8)
                {
                    return(null);
                }
                length    = (int)builder.ToUInt64(maskIndex, Endians.Big);
                maskIndex = maskIndex + 8;
            }
            else if (length == 126)
            {
                if (builder.Length < maskIndex + 2)
                {
                    return(null);
                }
                length    = (int)builder.ToUInt16(maskIndex, Endians.Big);
                maskIndex = maskIndex + 2;
            }

            // 检查数据长度
            if (builder.Length < maskIndex + Math.Max(4, length))
            {
                return(null);
            }

            // 数据内容的索引位置
            var dataIndex = maskIndex + 4;

            if (length > 0)
            {
                fixed(byte *pdata = &builder.Source[dataIndex], pmask = &builder.Source[maskIndex])
                {
                    for (var i = 0; i < length; i++)
                    {
                        *(pdata + i) = (byte)(*(pdata + i) ^ *(pmask + i % 4));
                    }
                }
            }

            // 将数据放到resultBuilder
            resultBuilder.Add(builder.Source, dataIndex, length);
            // 清除已分析的数据
            builder.Remove(dataIndex + length);

            // 检查数据是否传输完成
            if (isFinal == true && frameType != FrameTypes.Continuation)
            {
                var bytes = resultBuilder.ToArrayThenClear();
                return(new RequestPacket(frameType, bytes));
            }
            else
            {
                return(null);
            }
        }
Beispiel #28
0
    // Update is called once per frame
    void Update()
    {
        //死亡则慢慢下沉消失
        if (humanController.health <= 0 && !isDead)
        {
            if (dieCallbacks != null)
            {
                dieCallbacks(gameObject);                        //死亡回调
            }
            isDead = true;
            Destroy(GetComponent <CharacterController>());
            Destroy(GetComponent <Rigidbody>());
            Destroy(GetComponent <SphereCollider>());
            StopAllCoroutines();
            StartCoroutine(Die());
            return;
        }
        if (humanController.health != humanController.MaxHealth && humanController.health > 0 && !isTrace && !isShoot)
        {
            isTrace  = true;
            isPatrol = false;
            isShoot  = false;
        }

        if (isInRotate)
        {
            return;
        }
        // Debug.Log("Next");
        if (!isDead)
        {
            //移动
            if (isPatrol)
            {
                // Debug.Log("WALK");
                // nav.enabled = false;
                // StopCoroutine("Trace");
                humanController.Idle();
                if (Vector3.Angle(patrolForward, transform.forward) > 5.0f)  //判断是否需要转向
                {
                    // Debug.Log("ChangeTo:"+patrolForward + transform.forward + (patrolForward == transform.forward) +" "+);
                    // StopCoroutine("RotateByFrame");
                    RotateTowards(patrolForward);
                    return;
                }
                humanController.Walk(walkSpeed, 0f);
            }
            else if (isTrace)    //追踪
            {
                if (playerLastPosition == Vector3.zero || (Global.player.transform.position - playerLastPosition).magnitude > 3f)
                {
                    /*向服务器发送路径计算请求 */
                    byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_REQUEST));
                    byteBuilder.Add(System.BitConverter.GetBytes(id));
                    byteBuilder.Add(System.BitConverter.GetBytes(Network.SEARCH_ROAD));
                    byteBuilder.Add(System.BitConverter.GetBytes((int)(transform.position.x + 0.5)));
                    byteBuilder.Add(System.BitConverter.GetBytes((int)(transform.position.z + 0.5)));
                    byteBuilder.Add(System.BitConverter.GetBytes((int)(Global.player.transform.position.x + 0.5)));
                    byteBuilder.Add(System.BitConverter.GetBytes((int)(Global.player.transform.position.z + 0.5)));
                    Global.network.Send(byteBuilder.GetByes());
                    byteBuilder.Clear();
                    // nav.enabled = true;
                    // nav.SetDestination(Global.player.transform.position);
                    // humanController.Run(0, 0);
                    playerLastPosition = Global.player.transform.position;
                }
            }
            else if (vertical != 0 || horizontal != 0)
            {
                humanController.Run(vertical * runSpeed, horizontal * runSpeed);
                // nav.enabled = false;
                StopCoroutine("Trace");
                humanController.Idle();
            }
            else
            {
                // humanController.Idle();
                // nav.enabled = false;
                // StopCoroutine("Trace");
                StopAllCoroutines();
                humanController.Idle();
            }

            //设置视线
            Ray tar = new Ray(transform.position + shootRectify, transform.forward);
            if (Physics.Raycast(tar, out sightHit))
            {
                lookAtPoint = sightHit.point;
            }

            //检测是否玩家在视线内
            Vector3 targetV = Global.player.transform.position - transform.position;
            // Debug.Log(Vector3.Angle(transform.forward, targetV));
            if (Vector3.Angle(transform.forward, targetV) <= sightAngle)
            {
                Ray        detect = new Ray(transform.position + shootRectify, targetV);
                RaycastHit h;
                if (Physics.Raycast(detect, out h))
                {
                    // Debug.Log("Hit:"+h.collider.gameObject.layer+" "+h.collider.name);
                    // Debug.DrawRay(transform.position, targetV, Color.black);
                    if (h.collider.gameObject.layer == 11)
                    {
                        // Debug.Log("Human");
                        float dis = (transform.position - Global.player.transform.position).magnitude;
                        if (!isTrace && !isShoot)    //若在巡逻状态
                        {
                            Debug.Log("In Sight");
                            //在视线内
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_REQUEST));
                            byteBuilder.Add(System.BitConverter.GetBytes(id));
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.PLAYER_IN_SIGHT));
                            Global.network.Send(byteBuilder.GetByes());
                            byteBuilder.Clear();
                        }
                        else if (!isShoot && dis < weaponController.maxAttackDis)    //若不在射击状态
                        {
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_REQUEST));
                            byteBuilder.Add(System.BitConverter.GetBytes(id));
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.PLAYER_IN_SHOOT));
                            Global.network.Send(byteBuilder.GetByes());
                            byteBuilder.Clear();
                        }
                        else if (isShoot && dis > weaponController.maxAttackDis) //若在射击状态但不在攻击距离内
                        {
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_REQUEST));
                            byteBuilder.Add(System.BitConverter.GetBytes(id));
                            byteBuilder.Add(System.BitConverter.GetBytes(Network.PLAYER_OUT_SHOOT));
                            Global.network.Send(byteBuilder.GetByes());
                            byteBuilder.Clear();
                        }
                    }
                    else if (isShoot)    //出视线外
                    {
                        byteBuilder.Add(System.BitConverter.GetBytes(Network.RIVAL_REQUEST));
                        byteBuilder.Add(System.BitConverter.GetBytes(id));
                        byteBuilder.Add(System.BitConverter.GetBytes(Network.PLAYER_OUT_SHOOT));
                        Global.network.Send(byteBuilder.GetByes());
                        byteBuilder.Clear();
                    }
                }
            }

            //shoot
            if (isShoot)
            {
                Debug.Log("SHOOT");
                //若无子弹则换弹
                if (weaponController.bulletNumNow <= 0)
                {
                    weaponController.bulletSum = weaponController.bulletMaxHold + 100;  //设置子弹无限
                    humanController.Reload();
                }
                else
                {
                    transform.LookAt(Global.player.transform, transform.up);
                    if (humanController.Attack1() && weaponController.Shoot())
                    {
                        Ray ray = new Ray(transform.position + shootRectify, transform.forward + transform.right * Random.Range(-shootBias, shootBias) + transform.up * Random.Range(-shootBias, shootBias));
                        if (Physics.Raycast(ray, out hit))
                        {
                            //若击中环境,刀子无击中效果
                            if (hit.collider.gameObject.layer == 9 && weaponController.category != WeaponCategory.Knife)
                            {
                                GameObject shootSmoke = Instantiate(shootSmokePrefab, hit.point, Quaternion.identity);
                                shootSmoke.transform.localRotation.SetLookRotation(hit.normal);
                                //获取击中物体的颜色
                                Color          color          = hit.collider.gameObject.GetComponent <MeshRenderer>().material.color;
                                ParticleSystem particleSystem = shootSmoke.GetComponent <ParticleSystem>();
                                //设置起始颜色
                                ParticleSystem.MainModule main = particleSystem.main;
                                main.startColor = color;
                                //设置颜色渐变
                                ParticleSystem.ColorOverLifetimeModule col = particleSystem.colorOverLifetime;
                                col.enabled = true;
                                Gradient grad = new Gradient();
                                grad.SetKeys(new GradientColorKey[] { new GradientColorKey(color, 0.4f), new GradientColorKey(color, 1.0f) }, new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) });
                                col.color = grad;

                                GameObject.Destroy(shootSmoke, 0.5f);   //设置0.2s后销毁烟雾效果
                            }
                            //若击中人
                            else if (hit.collider.gameObject.layer == 11)
                            {
                                hit.collider.gameObject.GetComponent <HumanAnimController>().Damaged(weaponController.damage, hit.point);
                            }
                        }
                    }
                }
            }
        }
    }