Ejemplo n.º 1
0
    private void RecHandler(byte[] buf, ASynServerKcp serverKcp)
    {
        int playerId = BitConverter.ToInt32(buf, 0);

        serverKcp.PlayerId = playerId;
        MsgID        msgId  = (MsgID)BitConverter.ToInt32(buf, 4);
        MemoryStream stream = new MemoryStream(buf, 8, buf.Length - 8);
        IMessage     msg    = null;

        switch (msgId)
        {
        case MsgID.LoginReq:
            msg = LoginReq.Parser.ParseFrom(stream);
            break;

        case MsgID.LoginOutReq:
            msg = LoginOutReq.Parser.ParseFrom(stream);
            break;

        case MsgID.SteerPositionReq:
            //msg = SteerPositionReq.Descriptor.Parser.ParseFrom(stream);
            msg = SteerPositionReq.Parser.ParseFrom(stream);
            break;

        default:
            Log4U.LogDebug("SimulateServerUDP:RecHandler Not handler msgId=", msgId);
            break;
        }
        stream.Dispose();
        Log4U.LogDebug("SimulateServerUDP:RecHandler<<<<<< playerId=", playerId, " msgId=", msgId, " msg=", msg);
        MessageDispatcher.GetInstance().DispatchMessageAsyn(msgId, msg, playerId);
    }
Ejemplo n.º 2
0
 void SendMobilePollRequest(string DeviceID, int MsgId)
 {
     try
     {
         request             = (HttpWebRequest)HttpWebRequest.Create(conf.CPassServer + "/Api/Authorization/CpassAuth1Poll");
         request.ContentType = "application/json; charset=utf-8";
         request.Accept      = "application/json, text/javascript, */*";
         request.Method      = "POST";
         request.Headers.Add("Authorization", "Bearer " + conf.CPassKey);
         using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
         {
             writer.Write(@"{""requestId"": """ +
                          MsgID.ToString() +
                          @""",""dateTime"": """ +
                          dt +
                          @""",""cpass_UTN"":""" +
                          DeviceID +
                          @""",""tagid"": """ +
                          DeviceID +
                          @""",""pumP_ID"": ""1"",""fuel_Type_code"": ""0"",""nR_ID"": ""101"",""odometer"": ""0"",""engine_Hours"": ""0""}");
         }
         request.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
     }
     catch (Exception ex)
     {
         myLog.Log(ex.Message);
     }
 }
Ejemplo n.º 3
0
 public static void BroadCast <T>(Dictionary <string, Account> accs, MsgID id, T msg)
 {
     foreach (Account acc in accs.Values)
     {
         NetworkManager.Send(acc.client, (int)id, msg);
     }
 }
Ejemplo n.º 4
0
 public void Set(MsgID msgID, uint cmd, Google.Protobuf.IMessage T)
 {
     if (!mNetDict.ContainsKey(msgID))
     {
         mNetDict[msgID] = new Dictionary <uint, Google.Protobuf.IMessage>();
     }
     mNetDict[msgID][cmd] = T;
 }
Ejemplo n.º 5
0
    public static MsgBase Create(MsgID msgID)
    {
        switch (msgID)
        {
        case MsgID.Test: return(new MsgTest());

        default: return(null);
        }
    }
Ejemplo n.º 6
0
        protected override bool ShouldBlockMsg(MsgID msgID)
        {
            bool shouldBlock = this._accreditedMsgID != msgID && !this.accredited;

            if (shouldBlock)
            {
                this.Close(true, $"illegal session, msgID:{msgID}");
            }
            return(shouldBlock);
        }
Ejemplo n.º 7
0
    public static MsgBase Unpack(byte[] data)
    {
        MemoryStream bodyStream = new MemoryStream(data);
        BinaryReader reader     = new BinaryReader(bodyStream);
        MsgID        msgID      = (MsgID)reader.ReadInt32();
        MsgBase      msg        = MessageFactory.Create(msgID);

        msg.Unpack(reader);
        return(msg);
    }
Ejemplo n.º 8
0
 public Google.Protobuf.IMessage Query(MsgID msgID, uint cmd)
 {
     Google.Protobuf.IMessage T = null;
     if (!mNetDict.ContainsKey(msgID))
     {
         mNetDict[msgID] = new Dictionary <uint, Google.Protobuf.IMessage>();
     }
     mNetDict[msgID].TryGetValue(cmd, out T);
     return(T);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 查询并获得回执
        /// </summary>
        /// <typeparam name="T1">请求类</typeparam>
        /// <typeparam name="T2">返回类</typeparam>
        /// <param name="req">请求参数</param>
        /// <param name="wait_id">等待这个包回传</param>
        /// <param name="reply">回传</param>
        /// <returns></returns>
        private ErrorDef req_wait_reply <T1, T2>(T1 req, MsgID wait_id, out T2 reply) where T1 : IMessage <T1> where T2 : IMessage <T2>, new()
        {
            reply = default(T2);
            ErrorDef result_err = ErrorDef.Ok;

            byte[] req_bytes = Codec.Encode(req);
            result_err = write(req_bytes);
            if (result_err != ErrorDef.Ok)
            {
                return(result_err);
            }

            //超过这个时间
            int timeout = 10000;

            result_err = ErrorDef.TimeoutErr;
            T2 _reply = default(T2);
            Action <MsgID, byte[]> action = (msg_id, data) =>
            {
                MessageParser <T2> parser = new MessageParser <T2>(() => new T2());
                _reply     = parser.ParseFrom(data);
                timeout    = 0;
                result_err = ErrorDef.Ok;
            };

            WaitPack pack = new WaitPack();

            pack.action = action;
            pack.msg_id = wait_id;

            lock (wait_pack_look)
            {
                wait_pack.AddLast(pack);
            }

            Thread wait_th = new Thread((o) =>
            {
                while (timeout > 0)
                {
                    Thread.Sleep(50);
                    timeout -= 50;
                }
            });

            wait_th.Start();
            wait_th.Join();

            lock (wait_pack_look)
            {
                wait_pack.Remove(pack);
            }
            reply = _reply;

            return(result_err);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 查询并获得回执
        /// </summary>
        /// <typeparam name="T1">请求类</typeparam>
        /// <typeparam name="T2">返回类</typeparam>
        /// <param name="req">请求参数</param>
        /// <param name="wait_id">等待这个包回传</param>
        /// <param name="reply">回传</param>
        /// <returns></returns>
        private ErrorDef req_wait_reply <T1, T2>(T1 req, MsgID wait_id, out T2 reply)
        {
            reply = default(T2);
            ErrorDef result_err = ErrorDef.Ok;

            byte[] req_bytes = Codec.Encode(req);
            result_err = write(req_bytes);
            if (result_err != ErrorDef.Ok)
            {
                return(result_err);
            }

            //超过这个时间
            int timeout = 3000;

            result_err = ErrorDef.TimeoutErr;
            T2 _reply = default(T2);
            Action <MsgID, string> action = (msg_id, content) =>
            {
                _reply     = JsonConvert.DeserializeObject <T2>(content);
                timeout    = 0;
                result_err = ErrorDef.Ok;
            };

            WaitPack pack = new WaitPack();

            pack.action = action;
            pack.msg_id = wait_id;

            lock (wait_pack_look)
            {
                wait_pack.AddLast(pack);
            }

            Thread wait_th = new Thread((o) =>
            {
                while (timeout > 0)
                {
                    Thread.Sleep(50);
                    timeout -= 50;
                }
            });

            wait_th.Start();
            wait_th.Join();

            lock (wait_pack_look)
            {
                wait_pack.Remove(pack);
            }
            reply = _reply;

            return(result_err);
        }
Ejemplo n.º 11
0
 public void UnregisterHandler(MsgID messageId, Handle handler)
 {
     if (m_dict.ContainsKey(messageId))
     {
         m_dict[messageId] -= handler;
     }
     else
     {
         Debug.LogError("Unable to find handler : " + messageId);
     }
 }
 public void RemoveMessageListener(MsgID msgId, Action <IMessage, object> handler)
 {
     if (_msgDic.ContainsKey(msgId))
     {
         List <Action <IMessage, object> > list = _msgDic[msgId];
         if (list.Contains(handler))
         {
             list.Remove(handler);
         }
     }
 }
Ejemplo n.º 13
0
 public void UnregisterHandler(MsgID messageId, Handle handler)
 {
     if (msgHandle.ContainsKey(messageId))
     {
         msgHandle[messageId] -= handler;
     }
     else
     {
         Debug.LogErrorFormat("Unable to find handler : {0}", messageId);
     }
 }
 public void DispatchMessage(MsgID msgId, IMessage msg, object ext = null)
 {
     if (_msgDic.ContainsKey(msgId))
     {
         List <Action <IMessage, object> > list = _msgDic[msgId];
         foreach (Action <IMessage, object> handler in list)
         {
             handler(msg, ext);
         }
     }
 }
 public void DispatchMessageAsyn(MsgID msgId, IMessage msg, object ext = null)
 {
     lock (_receiveMessageQueue)
     {
         MessageArgs args = new MessageArgs();
         args.msgId = msgId;
         args.msg   = msg;
         args.ext   = ext;
         _receiveMessageQueue.Enqueue(args);
     }
 }
Ejemplo n.º 16
0
 public void RegisterHandler(MsgID messageId, Handle handler)
 {
     if (!m_dict.ContainsKey(messageId))
     {
         m_dict[messageId] = handler;
     }
     else
     {
         m_dict[messageId] += handler;
     }
 }
Ejemplo n.º 17
0
 //public bool Add(MsgID msgID, uint cmd, Google.Protobuf.IMessage T)
 //{
 //    //Google.Protobuf.IMessage 之间的相加
 //    return true;
 //}
 public Google.Protobuf.IMessage Del(MsgID msgID, uint cmd)
 {
     Google.Protobuf.IMessage T = null;
     if (mNetDict.ContainsKey(msgID))
     {
         if (mNetDict[msgID].ContainsKey(cmd))
         {
             T = mNetDict[msgID][cmd];
             mNetDict[msgID].Remove(cmd);
         }
     }
     return(T);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// 当收到网络消息
        /// </summary>
        /// <param name='cMsgType'>消息类型</param>
        /// <param name='pMsg'>消息数据</param>
        /// <param name='len'>数据长度</param>
        void OnNetMessage(ushort cMsgType, byte[] pMsg, int len)
        {
            switch (cMsgType)
            {
            case NetMsg.CLIENT_SERVER_RES:
                DEBUG.Networking(DEBUG.RECV_MSG_LOG + MsgID.ToString(cMsgType));
                HanldeGateSeverRes(pMsg, len);
                break;

            default:
                DEBUG.Networking(DEBUG.TRACER_LOG + "未处理的接收消息类型:" + MsgID.ToString(cMsgType), LogType.Warning);
                break;
            }
            NetworkMgr.Instance.OnNetMessage(cMsgType);
        }
Ejemplo n.º 19
0
    public override void HandleMsg(Pack pack)
    {
        MsgID msgID = (MsgID)pack.MessageID;

        if (msgID == MsgID.FrameInfoID && (_msgCache.Count > 0 || enableSimLatency))
        {
            PackInfo info = new PackInfo();
            info.pack     = pack;
            info.recvTime = Time.time;
            _msgCache.Enqueue(info);
            return;
        }

        base.HandleMsg(pack);
    }
Ejemplo n.º 20
0
    public void SendMsgToAll(MsgID msgId, IMessage msg)
    {
        Log4U.LogDebug("SimulateServerUDP:SendMsgToAll>>>>>> msgId=", msgId, " msg=", msg);
        byte[] msgIdBytes = BitConverter.GetBytes((int)msgId);
        byte[] msgBytes   = msg.ToByteArray();
        int    bufferSize = msgIdBytes.Length + msgBytes.Length;

        byte[] sendBuf = new byte[bufferSize];
        int    offset  = 0;

        Array.Copy(msgIdBytes, 0, sendBuf, offset, msgIdBytes.Length);
        offset += msgIdBytes.Length;
        Array.Copy(msgBytes, 0, sendBuf, offset, msgBytes.Length);
        _socket.SendToAll(sendBuf);
    }
Ejemplo n.º 21
0
    Pack SerializeToPack <T>(uint type, T content, MsgID msg_id) where T : ProtoBuf.IExtensible
    {
        using (MemoryStream msgBodyStream = new MemoryStream())
        {
            ProtoBuf.Serializer.Serialize <T>(msgBodyStream, content);

            msgBodyStream.Seek(0, SeekOrigin.Begin);

            Pack pack = GenerateHeader(type, (uint)msg_id, (uint)msgBodyStream.Length, m_type);

            pack.buffer = new byte[msgBodyStream.Length];
            msgBodyStream.Read(pack.buffer, 0, pack.buffer.Length);// ���õ�ǰ����λ��Ϊ���Ŀ�ʼ

            return(pack);
        }
    }
Ejemplo n.º 22
0
        public int send(byte[] data, bool bEncrypt)
        {
            int ir = -3;

            if (null != data)
            {
                try
                {
                    string s = MsgID.ToString(data[1]);
                    s += ("  长度: " + data.Length);
                    s += "  数据:";

                    for (int i = 0; i < data.Length; ++i)
                    {
                        s += (" " + data[i].ToString("X2"));
                    }

                    ////// TODO 查看发送十六进制数据(底层发送十六进制消息)
                    if (MahjongLobby_SX_Changzhi.LobbyContants.isOpenDebugMessage_Send)
                    {
                        Debug.Log("+++++++++++++++++++++" + s);
                    }

                    //DEBUG.NetworkClient(data[1], data);
                    byte[] pMsg = (bEncrypt) ? AESCrypt.Encrypt(data, AESCrypt.KEY) : data;
                    if (null != pMsg)
                    {
                        short  iMsgLen = (short)(pMsg.Length + 4);
                        byte[] msg     = new byte[iMsgLen];
                        msg[0]  = PACKAGE_IDENTIFY;
                        msg[1]  = (byte)((bEncrypt) ? 0 : 1);
                        iMsgLen = IPAddress.HostToNetworkOrder(iMsgLen);
                        byte[] len = BitConverter.GetBytes(iMsgLen);
                        Array.Copy(len, 0, msg, 2, len.Length);
                        Array.Copy(pMsg, 0, msg, 4, pMsg.Length);

                        ir = send(msg);
                    }
                }
                catch (Exception e)
                {
                    DEBUG.Networking(DEBUG.TRACER_LOG + "NetConnection.send, exp: " + e.Message, LogType.Exception);
                }
            }

            return(ir);
        }
Ejemplo n.º 23
0
        protected override void DispatchMessage(MsgID msgID, IMessage message)
        {
            MessageHandler handler = this.GetMsgHandler(msgID);

            if (handler != null)
            {
                ErrorCode errorCode = handler.Invoke(this, message);
                if (errorCode != ErrorCode.Success)
                {
                    Logger.Warn(errorCode);
                }
            }
            else
            {
                this.Close(true, $"unhandle msg:{msgID}.");
            }
        }
Ejemplo n.º 24
0
    protected override bool _RecvPack(ref List <Pack> outPacks, Stream stream)
    {
        lock (stream)
        {
            try
            {
                stream.Seek(0, SeekOrigin.Begin);
                while (true)
                {
                    Pack inPack = new Pack();
                    inPack.headerBuffer = new byte[Pack.HeaderLength];
                    int read = stream.Read(inPack.headerBuffer, 0, Pack.HeaderLength);
                    if (read == 0)
                    {
                        break;
                    }
                    inPack.ParseHeader();
                    inPack.buffer = new byte[inPack.Length];
                    read          = stream.Read(inPack.buffer, 0, inPack.buffer.Length);
                    decrypt(inPack);
#if UNITY_EDITOR
                    MsgID msg_id = (MsgID)inPack.MessageID;
                    if (!MsgHandler.m_noLogMsg.Contains(msg_id))
                    {
                        Debug.Log("-------_RecvPack with MessageID11: " + msg_id.ToString());
                    }
#endif
                    outPacks.Add(inPack);
                }
                stream.Seek(0, SeekOrigin.Begin);
                stream.SetLength(0);
            }
            catch (Exception exp)
            {
                m_curBufferPos = 0;
                Debug.LogError("network conn exception: " + exp.Message);
                stream.Seek(0, SeekOrigin.Begin);
                stream.SetLength(0);

                return(false);
            }
        }
        //Debug.Log("outPacks count " + outPacks.Count);

        return(outPacks.Count != 0);
    }
 public void AddMessageListener(MsgID msgId, Action <IMessage, object> handler)
 {
     if (_msgDic.ContainsKey(msgId))
     {
         List <Action <IMessage, object> > list = _msgDic[msgId];
         if (!list.Contains(handler))
         {
             list.Add(handler);
         }
     }
     else
     {
         List <Action <IMessage, object> > list = new List <Action <IMessage, object> >();
         list.Add(handler);
         _msgDic.Add(msgId, list);
     }
 }
Ejemplo n.º 26
0
    /// <summary>
    /// 记录接收服务器的消息数据
    /// </summary>
    /// <param name='id'>
    /// 消息类型
    /// </param>
    /// <param name='bytes'>
    /// 消息的字节数组
    /// </param>
    public static void NetworkServer(ushort id, byte[] bytes)
    {
        if (MsgID.SkipLog(id))
        {
            return;
        }

        string s = MsgID.ToString(id);

        s += ("  长度: " + bytes.Length);
        s += "  数据:";
        for (int i = 0; i < bytes.Length; ++i)
        {
            s += (" " + bytes[i].ToString("X2"));
        }
        //Debug.Log(s);
        NetworkServer(s);
    }
Ejemplo n.º 27
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (MsgID != 0)
            {
                hash ^= MsgID.GetHashCode();
            }
            if (Userid != 0)
            {
                hash ^= Userid.GetHashCode();
            }
            if (Username.Length != 0)
            {
                hash ^= Username.GetHashCode();
            }
            return(hash);
        }
Ejemplo n.º 28
0
    /// <summary>
    /// 记录客户端发送的消息数据
    /// </summary>
    /// <param name='id'>
    /// 消息类型
    /// </param>
    /// <param name='bytes'>
    /// 消息的字节数组
    /// </param>
    public static void NetworkClient(ushort id, byte[] bytes)
    {
        if (MsgID.SkipLog(id))
        {
            //return;
        }

        string s = MsgID.ToString(id);

        s += ("  长度: " + bytes.Length);
        s += "  数据:";
        for (int i = 0; i < bytes.Length; ++i)
        {
            s += (" " + bytes[i].ToString("X2"));
        }

        NetworkClient(s);
    }
Ejemplo n.º 29
0
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="id"></param>
    public void SendMsg(MsgID id, Bundle bundle = null)
    {
        List <IMsgHandle> handlist;

        if (msgDict.TryGetValue(id, out handlist))
        {
            if (handlist != null && handlist.Count > 0)
            {
                // clear the null
                for (int i = 0; i < handlist.Count; i++)
                {
                    MonoBehaviour mono = handlist[i] as MonoBehaviour;
                    if (mono == null)
                    {
                        RemoveMsg(id, handlist[i]);
                    }
                }
                // do HandleMessage
                for (int i = 0; i < handlist.Count; i++)
                {
                    if (handlist[i] != null && (handlist[i] as MonoBehaviour) != null)
                    {
                        handlist[i].HandleMessage(id, bundle);
                    }
                    else
                    {
                        Debuger.Log("the MonoBehaviour is null!");
                    }
                }
            }
            else
            {
                msgDict.Remove(id);
                Debuger.Log("the hand list is null!");
            }
        }
        else
        {
            msgDict.Remove(id);
            Debuger.Log("the hand list is null!");
        }
    }
Ejemplo n.º 30
0
    /// <summary>
    /// 注册消息
    /// </summary>
    /// <param name="id"></param>
    /// <param name="handle"></param>
    public void RegistMsg(MsgID id, IMsgHandle handle)
    {
        List <IMsgHandle> handlist;

        if (msgDict.ContainsKey(id))
        {
            msgDict.TryGetValue(id, out handlist);
            if (handlist == null)
            {
                handlist = new List <IMsgHandle>();
            }
            handlist.Add(handle);
        }
        else
        {
            handlist = new List <IMsgHandle>();
            handlist.Add(handle);
            msgDict.Add(id, handlist);
        }
    }