mirror of
https://github.com/StarBeat/JsonRpc.git
synced 2026-03-08 12:05:29 +08:00
72 lines
2.1 KiB
C#
72 lines
2.1 KiB
C#
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);
|
|
}
|
|
|
|
}
|
|
}
|