JsonRpc/JsonRPC/RPC/Receiver.cs

72 lines
2.1 KiB
C#
Raw Permalink Normal View History

2025-10-14 21:05:08 +08:00
using JsonRPC.Protocol;
using Newtonsoft.Json;
namespace JsonRPC.RPC
{
public class Receiver : AbsSingle<Receiver>
{
Dictionary<string, Func<JsonRPCRequest, JsonRPCResponse>> handlers = new();
public void RegHandler(string methodSig, Func<JsonRPCRequest, JsonRPCResponse> func)
{
handlers.Add(methodSig, func);
}
public string OnReceive(string msg)
{
JsonRPCResponse response;
var req = JsonConvert.DeserializeObject<JsonRPCRequest>(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);
}
}
}