/// <summary> /// 等待并获取任务结果 /// </summary> /// <param name="taskId"></param> /// <param name="e"></param> private void GetTaskWaitReslut(string taskId, HttpRequestEventArgs e, Stopwatch sw) { try { if (sw.ElapsedMilliseconds > HeartBeatSecond) { //超过心跳 则返回给客户端,以便下次继续请求 HttpResponse(e, new WSResModel(ResCode.Wait)); return; } //获取任务状态 WSResModel resModel = HandlerTaskManager.GetTaskReslut(taskId); if (resModel != null) { HttpResponse(e, resModel); } else { Thread.Sleep(50); GetTaskWaitReslut(taskId, e, sw); } } catch (Exception ex) { HttpResponse(e, new WSResModel(ResCode.Err, string.Format("服务器内部异常:{0}", ex.Message))); } }
/// <summary> /// 结果返回给客户端并断开链接 /// </summary> /// <param name="msg"></param> public void SendAndClose(WSResModel resModel) { try { string json = Newtonsoft.Json.JsonConvert.SerializeObject(resModel); this.Send(json); try { this.Context.WebSocket.Close(); } catch (Exception ex) { } } catch (Exception ex) { CommonInfo.Output("发送消息异常:{0}", ex.Message); } }
/// <summary> /// Http响应客户端 /// </summary> /// <param name="e"></param> /// <param name="resMsg"></param> private void HttpResponse(HttpRequestEventArgs e, WSResModel resModel) { try { string json = Newtonsoft.Json.JsonConvert.SerializeObject(resModel); byte[] content = System.Text.Encoding.UTF8.GetBytes(json); e.Response.StatusCode = (int)HttpStatusCode.OK; e.Response.AddHeader("Access-Control-Allow-Origin", "*");//允许跨域访问 e.Response.ContentEncoding = Encoding.UTF8; e.Response.ContentLength64 = content.Length; e.Response.OutputStream.Write(content, 0, content.Length); e.Response.OutputStream.Close(); e.Response.Close(); } catch (Exception ex) { CommonInfo.Output("Http响应客户端异常:{0}", ex.Message); } }