/// <summary> /// 获取通过网络传输对象时的json格式的字节数组 /// </summary> /// <param name="p_obj">待传输对象</param> /// <returns>字节数组</returns> public static byte[] GetObjectBytes(object p_obj) { if (p_obj == null) { throw new ArgumentNullException(nameof(p_obj)); } using (var stream = new MemoryStream()) { using (var writer = new Utf8JsonWriter(stream, JsonOptions.UnsafeWriter)) { JsonRpcSerializer.Serialize(p_obj, writer); } return(stream.ToArray()); } }
/// <summary> /// 向客户端输出响应 /// </summary> /// <param name="p_responseType">结果标志:0成功,1错误,2警告提示</param> /// <param name="p_elapsed">耗时</param> /// <param name="p_content">内容</param> /// <returns></returns> public Task Response(ApiResponseType p_responseType, long p_elapsed, object p_content) { try { byte[] data; using (var stream = new MemoryStream()) { using (var writer = new Utf8JsonWriter(stream, JsonOptions.UnsafeWriter)) { writer.WriteStartArray(); // 0成功,1错误,2警告提示 writer.WriteNumberValue((int)p_responseType); // 耗时 writer.WriteNumberValue(p_elapsed); // 内容 JsonRpcSerializer.Serialize(p_content, writer); writer.WriteEndArray(); } data = stream.ToArray(); } bool compress = data.Length > RpcKit.MinCompressLength; // 超过长度限制时执行压缩 if (compress) { var ms = new MemoryStream(); using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress)) { zs.Write(data, 0, data.Length); } data = ms.ToArray(); } // 写入响应流 return(RpcServerKit.WriteFrame(Context.Response.BodyWriter, data, compress)); } catch (Exception ex) { Log.Error(ex, "向客户端输出信息时异常!"); } return(Task.CompletedTask); }
/// <summary> /// 获取Rpc调用时json格式的字节数组 /// </summary> /// <param name="p_methodName">方法名</param> /// <param name="p_params">参数</param> /// <param name="p_indented">序列化json时是否含有缩进</param> /// <returns>字节数组</returns> public static byte[] GetCallBytes(string p_methodName, ICollection <object> p_params, bool p_indented = false) { using (var stream = new MemoryStream()) { using (var writer = new Utf8JsonWriter(stream, p_indented ? JsonOptions.IndentedWriter : JsonOptions.UnsafeWriter)) { writer.WriteStartArray(); writer.WriteStringValue(p_methodName); if (p_params != null && p_params.Count > 0) { foreach (var par in p_params) { JsonRpcSerializer.Serialize(par, writer); } } writer.WriteEndArray(); } return(stream.ToArray()); } }