Example #1
0
        /// <summary>
        /// 向客户端写入一帧
        /// </summary>
        /// <param name="p_message">支持序列化的对象</param>
        /// <returns></returns>
        public async Task <bool> Write(object p_message)
        {
            // 请求已关闭,无法写入
            if (_invoker.Context.RequestAborted.IsCancellationRequested)
            {
                return(false);
            }

            try
            {
                await RpcServerKit.WriteFrame(_invoker.Context.Response.BodyWriter, p_message);

                return(true);
            }
            catch { }

            return(false);
        }
Example #2
0
        /// <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);
        }