Esempio n. 1
0
        public override object InvokeResult(object rq, Func <Type, object> objectCtor)
        {
            var request  = rq as RequestJsonMessage;
            var response = new ResponseJsonMessage();

            try
            {
                var msgBase = new Core.Remoting.MessageBase()
                {
                    Args = request.Args, Method = request.Method, Service = request.Service, Token = request.Token, ApiPrefix = request.ApiPrefix
                };
                var errorInfo = InvokeMessage(msgBase, out object result, out Dictionary <int, object> outs, out string token, objectCtor);
                if (errorInfo != null)
                {
                    return(ResponseJsonMessage.CreateError(errorInfo.msg, errorInfo.code));
                }
                response.SetData(result);
                response.Success = true;
                response.Outs    = outs;
                if (!string.IsNullOrEmpty(token))//登录方法后返回新TOKEN
                {
                    response.Token = token;
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Msg     = ex.Message;
                Console.WriteLine(ex.ToString());
                CRL.Core.EventLog.Log(ex.ToString(), request.Service);
                return(ResponseJsonMessage.CreateError(ex.Message + $" 在{request.Service}/{request.Method}", "500"));
            }

            return(response);
        }
Esempio n. 2
0
        public void Set(string key, ResponseJsonMessage response)
        {
            var wait = waits[key];

            wait.Response = response;
            wait.Set();
        }
Esempio n. 3
0
 public static HttpResponseMessage HttpRMtoJson(object obj, HttpStatusCode statusCode, customStatus customStatus)
 {
     string str;
     ResponseJsonMessage rjm = new ResponseJsonMessage(customStatus.ToString(), obj);
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     str = serializer.Serialize(rjm);
     HttpResponseMessage result = new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
     return result;
 }
Esempio n. 4
0
        internal void OnMessage(ResponseJsonMessage msg)
        {
            var a = subs.TryGetValue(msg.MsgType, out methodType method);

            if (a)
            {
                var dg   = method.action;
                var data = msg.GetData(method.type);
                dg.DynamicInvoke(data);
            }
        }
Esempio n. 5
0
 public static HttpResponseMessage HttpRMtoJson(string jsonpCallback, object obj, HttpStatusCode statusCode, customStatus customStatus)
 {
     string str;
     ResponseJsonMessage rjm = new ResponseJsonMessage(customStatus.ToString(), obj);
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     if(string.IsNullOrEmpty(jsonpCallback))
         str = serializer.Serialize(rjm);
     else
         str = jsonpCallback + "(" + serializer.Serialize(rjm) + ");";
     HttpResponseMessage result = new HttpResponseMessage() { StatusCode = statusCode, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
     return result;
 }
Esempio n. 6
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            IChannel ch = ctx.Channel;

            if (!this.handshaker.IsHandshakeComplete)
            {
                try
                {
                    this.handshaker.FinishHandshake(ch, (IFullHttpResponse)msg);
                    Console.WriteLine("WebSocket Client connected!");
                    this.completionSource.TryComplete();
                }
                catch (WebSocketHandshakeException e)
                {
                    Console.WriteLine("WebSocket Client failed to connect");
                    this.completionSource.TrySetException(e);
                }

                return;
            }


            if (msg is IFullHttpResponse response)
            {
                throw new InvalidOperationException(
                          $"Unexpected FullHttpResponse (getStatus={response.Status}, content={response.Content.ToString(Encoding.UTF8)})");
            }

            if (msg is TextWebSocketFrame textFrame)
            {
                var json = textFrame.Text();
                //Console.WriteLine($"WebSocket Client received message: {json}");
                //发送返回信号
                var response2 = ResponseJsonMessage.FromBuffer(json);
                if (!string.IsNullOrEmpty(response2.MsgId))
                {
                    waits.Set(response2.MsgId, response2);
                }
                else
                {
                    clientConnect.OnMessage(response2);
                }
            }
            else if (msg is PongWebSocketFrame)
            {
                Console.WriteLine("WebSocket Client received pong");
            }
            else if (msg is CloseWebSocketFrame)
            {
                Console.WriteLine("WebSocket Client received closing");
                ch.CloseAsync();
            }
        }
        public static HttpResponseMessage HttpRMtoJson(object obj, HttpStatusCode statusCode, ECustomStatus customStatus)
        {
            string str;
            ResponseJsonMessage rjm = new ResponseJsonMessage(customStatus.ToString(), obj);

            str = JsonConvert.SerializeObject(rjm);
            HttpResponseMessage result = new HttpResponseMessage()
            {
                StatusCode = statusCode, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return(result);
        }
Esempio n. 8
0
        public bool SendMessage <T>(string clientKey, T msg, out string error)
        {
            error = "";
            var a = clientKeys.TryGetValue(clientKey, out IChannelHandlerContext ctx);

            if (!a)
            {
                error = "找不到客户端连接";
                return(false);
            }
            var response = new ResponseJsonMessage()
            {
                Data = msg.ToJson(), MsgType = typeof(T).Name
            };
            var frame2 = new TextWebSocketFrame(response.ToJson());

            ctx.WriteAndFlushAsync(frame2);
            return(true);
        }
Esempio n. 9
0
        public object InvokeResult2(IChannelHandlerContext ctx, object rq, Func <Type, object> getArgs = null)
        {
            var request  = rq as RequestJsonMessage;
            var response = new ResponseJsonMessage();

            try
            {
                var msgBase = new Core.Remoting.MessageBase()
                {
                    Args = request.Args, Method = request.Method, Service = request.Service, Token = request.Token
                };
                var errorInfo = InvokeMessage(msgBase, out object result, out Dictionary <int, object> outs, out string token, getArgs);
                if (errorInfo != null)
                {
                    return(ResponseJsonMessage.CreateError(errorInfo.msg, errorInfo.code));
                }
                response.SetData(result);
                response.Success = true;
                response.Outs    = outs;
                if (!string.IsNullOrEmpty(token))//登录方法后返回新TOKEN
                {
                    response.Token = token;
                    var arry = response.Token.Split('@');
                    AddClient(ctx, arry[0]);
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Msg     = ex.Message;
                Console.WriteLine(ex.ToString());
                CRL.Core.EventLog.Log(ex.ToString(), request.Service);
                return(ResponseJsonMessage.CreateError(ex.Message + $" 在{request.Service}/{request.Method}", "500"));
            }

            return(response);
        }
Esempio n. 10
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var methodInfo = serviceInfo.GetMethod(binder.Name);
            var id         = Guid.NewGuid().ToString();
            var method     = ServiceType.GetMethod(binder.Name);
            var returnType = method.ReturnType;
            var request    = new RequestJsonMessage
            {
                Service = ServiceName,
                Method  = binder.Name,
                //Token = clientConnect.Token
            };
            var allArgs = method.GetParameters();
            var token   = request.Token;

            request.Token = CreateAccessToken(allArgs, args.ToList(), clientConnect.TokenInfo);
            request.Args  = args.ToList();
            ResponseJsonMessage response = null;

            try
            {
                response = ((WebSocketClientConnect)clientConnect).SendRequest(request);
            }
            catch (Exception ero)
            {
                ThrowError(ero.Message, "500");
            }
            if (response == null)
            {
                ThrowError("请求超时未响应", "500");
            }
            if (!response.Success)
            {
                ThrowError($"服务端处理错误:{response.Msg}", response.Data);
            }
            if (response.Outs != null && response.Outs.Count > 0)
            {
                foreach (var kv in response.Outs)
                {
                    var p     = allArgs[kv.Key];
                    var value = kv.Value;
                    if (p.Name.EndsWith("&"))
                    {
                        var name  = p.Name.Replace("&", "");
                        var type2 = Type.GetType(name);
                        value = value.ToString().ToObject(type2);
                    }
                    args[kv.Key] = value;
                }
            }
            if (!string.IsNullOrEmpty(response.Token))
            {
                clientConnect.TokenInfo.Token = response.Token;
            }
            if (returnType == typeof(void))
            {
                result = null;
                return(true);
            }
            var generType = returnType;

            if (methodInfo.IsAsync)
            {
                generType = returnType.GenericTypeArguments[0];
            }
            result = response.GetData(generType);
            if (methodInfo.IsAsync)
            {
                var result2 = result;
                var task    = methodInfo.TaskCreater();
                task.ResultCreater = async() =>
                {
                    return(await Task.FromResult(result2));
                };
                result = task.InvokeAsync();
            }
            return(true);
        }
Esempio n. 11
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var id              = Guid.NewGuid().ToString();
            var method          = ServiceType.GetMethod(binder.Name);
            var methodParamters = method.GetParameters();
            var returnType      = method.ReturnType;
            var request         = new RequestJsonMessage
            {
                Service = ServiceName,
                Method  = binder.Name,
                //Token = clientConnect.Token.Token
            };
            var allArgs = method.GetParameters();

            request.Args = args.ToList();
            ResponseJsonMessage response = null;

            try
            {
                response = SendRequest(methodParamters, request);
            }
            catch (Exception ero)
            {
                ThrowError(ero.Message, "500");
            }
            if (response == null)
            {
                ThrowError("请求超时未响应", "500");
            }
            if (!response.Success)
            {
                ThrowError($"服务端处理错误:{response.Msg}", response.Data);
            }
            if (response.Outs != null && response.Outs.Count > 0)
            {
                foreach (var kv in response.Outs)
                {
                    var p     = allArgs[kv.Key];
                    var value = kv.Value;
                    if (p.Name.EndsWith("&"))
                    {
                        var name  = p.Name.Replace("&", "");
                        var type2 = Type.GetType(name);
                        value = value.ToString().ToObject(type2);
                    }
                    args[kv.Key] = value;
                }
            }
            if (!string.IsNullOrEmpty(response.Token))
            {
                clientConnect.TokenInfo.Token = response.Token;
            }
            if (returnType == typeof(void))
            {
                result = null;
                return(true);
            }
            result = response.GetData(returnType);

            return(true);
        }