protected async Task <ResponseMsg> RequestAsync <TRequest, TResponse>(TRequest obj)
        {
            var requestMsg = new RequestMsg()
            {
                RequestTypeName   = typeof(TRequest).AssemblyQualifiedName,
                RequestObjectData = MsgPackTool.GetBytes(obj)
            };

            var reqData = MsgPackTool.GetBytes(requestMsg);

            var resData = await RequestAsync(reqData);

            if (resData == null)
            {
                return(default(ResponseMsg));
            }
            var resMsg = MsgPackTool.GetMsg <ResponseMsg>(resData);

            if (resMsg.IsError)
            {
                Logger.Error("Error on Request: {0}", resMsg.ErrorMessage);
            }

            return(resMsg);
        }
        //protected IEnumerator<TResponse> Request<TRequest, TResponse>(TRequest obj)
        //{
        //    var reqData = MsgPackTool.GetBytes(obj);
        //    var resData = Coroutine<byte[]>.Start(Request(reqData));
        //    while (!resData.IsFinished)
        //        yield return default(TResponse);

        //    if (resData.Result == null)
        //    {
        //        yield return default(TResponse);
        //        yield break;
        //    }
        //    yield return MsgPackTool.GetMsg<TResponse>(resData.Result);
        //}

        /// <summary>
        /// 创建请求消息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private byte[] CreateRequestMsg(byte[] obj)
        {
            var requestMsg = new BaseRequestMsg()
            {
                SessionToken = SessionToken,
                RequestToken = BaseNetMqServer.GenerateRequestKey(), //Path.GetRandomFileName(),
                Data         = obj,
            };

            return(MsgPackTool.GetBytes(requestMsg));
        }
Exemple #3
0
        protected override async Task <byte[]> ProcessRequest(byte[] reqData)
        {
            var t           = new TaskCompletionSource <byte[]>();
            var requestMsg  = MsgPackTool.GetMsg <RequestMsg>(reqData);
            var requestType = requestMsg.RequestType;
            var requestObj  = MsgPackTool.GetMsg(requestType, requestMsg.RequestObjectData);
            var resMsg      = new ResponseMsg();

            resMsg.IsError = false;

            RpcServiceFuncInfo funcInfo;

            if (!_serviceFuncs.TryGetValue(requestType, out funcInfo))
            {
                Logger.Error("Not found RequestType func: {0}", requestType);
                return(await t.Task);
            }
            var info   = _serviceFuncs[requestType];
            var method = info.Method;

            byte[] executeResult = null;

            if (method != null)
            {
                try
                {
                    var result = method.Invoke(_rpcService, new[] { requestObj });
                    if (result != null)
                    {
                        executeResult = MsgPackTool.GetBytes(method.ReturnType, result);
                    }
                }
                catch (Exception e)
                {
                    resMsg.IsError      = true;
                    resMsg.ErrorMessage = string.Format("[ERROR]Method '{0}' Exception: {1}", requestObj, e);
                    Logger.Error(resMsg.ErrorMessage);
                }
            }
            else
            {
                resMsg.IsError      = true;
                resMsg.ErrorMessage = string.Format("[ERROR]Not found method: {0}", requestObj);
                Logger.Error(resMsg.ErrorMessage);
            }

            resMsg.Data = executeResult;
            t.SetResult(MsgPackTool.GetBytes(resMsg));

            return(await t.Task);
        }
Exemple #4
0
 public RpcCallResult(ResponseMsg response)
 {
     Msg = response;
     if (response.IsError)
     {
     }
     if (response.Data == null)
     {
         Value = default(T);
     }
     else
     {
         Value = MsgPackTool.GetMsg <T>(response.Data);
     }
 }
Exemple #5
0
        public async Task <TRes> CallResultAsync <TReq, TRes>(TReq request)
        {
            var startTime = DateTime.UtcNow;

            Logger.Trace("[Start]Request: {0}, Response: {1}", request, typeof(TRes));

            //var proto = new RequestMsg
            //{
            //    FuncName = funcName,
            //    Arguments = arguments,
            //};
            var responseMsg = await RequestAsync <TReq, TRes>(request);

            Logger.Trace("[Finish]CallResult: {0} used time: {1:F5}s", request, (DateTime.UtcNow - startTime).TotalSeconds);

            return(MsgPackTool.GetMsg <TRes>(responseMsg.Data));
        }
        internal void OnRecvMsg(BaseZmqWorker worker, ZMessage recvMsg)
        {
            using (recvMsg)
            {
                var startTime = DateTime.UtcNow;
                using (recvMsg)
                {
                    var clientAddr     = recvMsg[0];
                    var clientData     = recvMsg[2].Read();
                    var baseRequestMsg = MsgPackTool.GetMsg <BaseRequestMsg>(clientData);
                    var requestDataMsg = baseRequestMsg.Data;

                    var responseTask = ProcessRequest(requestDataMsg);
                    responseTask.Wait();
                    var responseMsg = responseTask.Result;

                    // if no session key, generate new
                    var sessionToken = baseRequestMsg.SessionToken;
                    if (string.IsNullOrEmpty(sessionToken))
                    {
                        sessionToken = GenerateSessionKey();
                    }
                    var baseResponseMsg = new BaseResponseMsg()
                    {
                        SessionToken = sessionToken,
                        RequestToken = baseRequestMsg.RequestToken,
                        Data         = responseMsg,
                    };

                    var sendData = MsgPackTool.GetBytes(baseResponseMsg);

                    var messageToServer = new ZMessage();
                    messageToServer.Append(clientAddr);
                    messageToServer.Append(ZFrame.CreateEmpty());
                    messageToServer.Append(new ZFrame(sendData));
                    worker.workerSocket.SendMessage(messageToServer);
                }

                Logger.Trace("Receive Msg and Send used Time: {0:F5}s", (DateTime.UtcNow - startTime).TotalSeconds);
            }
        }
        //protected IEnumerator<byte[]> Request(byte[] obj)
        //{
        //    var retryCount = 5;
        //    while (retryCount > 0)
        //    {
        //        var bytes = CreateRequestMsg(obj);

        //        // We send a request, then we work to get a reply
        //        if (!_requestSocket.Send(new ZFrame(bytes), out error))
        //        {
        //            if (error == ZError.ETERM)
        //                continue;    // Interrupted
        //            throw new ZException(error);
        //        }
        //        var poll = ZPollItem.CreateReceiver();
        //        ZMessage incoming;

        //        bool result = false;
        //        var pollStartTime = DateTime.UtcNow;
        //        var timeoutTime = 5f;
        //        do
        //        {
        //            result = _requestSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(1));
        //        } while (
        //            !result &&
        //            (DateTime.UtcNow - pollStartTime).TotalSeconds < timeoutTime); // timeout

        //        if (!result)
        //        {
        //            Logger.Error("超时重试");
        //            if (error == ZError.EAGAIN)
        //            {
        //                if (--retryCount == 0)
        //                {
        //                    Console.WriteLine("E: server seems to be offline, abandoning");
        //                    break;
        //                }
        //                // Old socket is confused; close it and open a new one
        //                _requestSocket.Dispose();
        //                if (null == (_requestSocket = CreateSocket(out error)))
        //                {
        //                    if (error == ZError.ETERM)
        //                    {
        //                        Logger.Error("ETERM!");
        //                        break; // Interrupted
        //                    }
        //                    throw new ZException(error);
        //                }

        //                Console.WriteLine("I: reconnected");

        //                continue;
        //            }
        //            if (error == ZError.ETERM)
        //            {
        //                Logger.Error("ETERM!!");
        //                break; // Interrupted
        //            }
        //            throw new ZException(error);
        //        }
        //        else
        //        {
        //            using (incoming)
        //            {
        //                // We got a reply from the server
        //                //int incoming_sequence = incoming[0].ReadInt32();
        //                //var recvMessage = _requestSocket.ReceiveMessage();
        //                var recvMsg = MsgPackTool.GetMsg<BaseResponseMsg>(incoming[0].Read());
        //                _responses[recvMsg.RequestToken] = recvMsg;
        //                SessionToken = recvMsg.SessionToken;
        //                if (string.IsNullOrEmpty(SessionToken))
        //                    throw new Exception(string.Format("Error Session token when get response"));

        //                yield return recvMsg.Data;
        //                yield break;
        //            }
        //        }
        //    }

        //    yield return null;
        //}

        protected async Task <byte[]> RequestAsync(byte[] obj)
        {
            var retryCount = 50;

            while (retryCount > 0)
            {
                var bytes = CreateRequestMsg(obj);

                // We send a request, then we work to get a reply
                if (!_requestSocket.Send(new ZFrame(bytes), out error))
                {
                    if (error == ZError.ETERM)
                    {
                        continue;    // Interrupted
                    }
                    throw new ZException(error);
                }
                var      poll = ZPollItem.CreateReceiver();
                ZMessage incoming;


                bool result        = false;
                var  pollStartTime = DateTime.UtcNow;
                var  timeoutTime   = 5f;
                do
                {
                    await Task.Delay(1);

                    result = _requestSocket.PollIn(poll, out incoming, out error, TimeSpan.FromMilliseconds(1));
                } while (
                    !result &&
                    (DateTime.UtcNow - pollStartTime).TotalSeconds < timeoutTime); // timeout

                if (!result)
                {
                    Logger.Error("超时重试");
                    if (error == ZError.EAGAIN)
                    {
                        if (--retryCount == 0)
                        {
                            Console.WriteLine("E: server seems to be offline, abandoning");
                            break;
                        }
                        // Old socket is confused; close it and open a new one
                        _requestSocket.Dispose();
                        if (null == (_requestSocket = CreateSocket(out error)))
                        {
                            if (error == ZError.ETERM)
                            {
                                Logger.Error("ETERM!");
                                break; // Interrupted
                            }
                            throw new ZException(error);
                        }

                        Console.WriteLine("I: reconnected");

                        continue;
                    }
                    if (error == ZError.ETERM)
                    {
                        Logger.Error("ETERM!!");
                        break; // Interrupted
                    }
                    throw new ZException(error);
                }
                else
                {
                    using (incoming)
                    {
                        // We got a reply from the server
                        //int incoming_sequence = incoming[0].ReadInt32();
                        //var recvMessage = _requestSocket.ReceiveMessage();
                        var recvMsg = MsgPackTool.GetMsg <BaseResponseMsg>(incoming[0].Read());
                        _responses[recvMsg.RequestToken] = recvMsg;
                        SessionToken = recvMsg.SessionToken;
                        if (string.IsNullOrEmpty(SessionToken))
                        {
                            throw new Exception(string.Format("Error Session token when get response"));
                        }

                        return(recvMsg.Data);
                    }
                }
            }

            return(null);
        }