using JsonRPC.Protocol; using Newtonsoft.Json; namespace JsonRPC.RPC { public class Receiver : AbsSingle { Dictionary> handlers = new(); public void RegHandler(string methodSig, Func func) { handlers.Add(methodSig, func); } public string OnReceive(string msg) { JsonRPCResponse response; var req = JsonConvert.DeserializeObject(msg); if(req == null) { response = new JsonRPCResponse() { Error = new JsonRPCError() { Code = (int)EErrorCode.ParseError, Message = msg, Data = "invalid json." } }; return JsonConvert.SerializeObject(response); } if (handlers.TryGetValue(req.Method, out var handler)) { try { response = handler!(req); } catch (Exception e) { response = new JsonRPCResponse() { Id = req.Id, Error = new JsonRPCError() { Code = (int)EErrorCode.InternalError, Message = msg, Data = e.ToString() } }; } } else { response = new JsonRPCResponse() { Id = req.Id, Error = new JsonRPCError() { Code = (int)EErrorCode.MethodNotFound, Message = msg, } }; } return JsonConvert.SerializeObject(response); } } }