/// <summary> /// 返回给客户端 /// </summary> /// <param name="resModel"></param> public void ReturnToClient(WSResModel resModel) { try { if (resModel == null) { return; } this.OutPara = resModel; this.ReturnTime = DateTime.Now; if (ReqIsWebSocket) { //WebSocket 根据任务Id(TaskId)查找链接 进行返回 WebSocketServiceHost host; if (WSMain.Instance.HttpServer.WebSocketServices.TryGetServiceHost(string.Format("/{0}", this.Path), out host) && host != null) { foreach (IWebSocketSession item in host.Sessions.Sessions) { MyWebSocketBehavior session = item as MyWebSocketBehavior; if (session != null && session.TaskId == this.TaskId) { session.SendAndClose(this.OutPara); //从队列中移除 HandlerTaskManager.Remove(this.TaskId); } } } } } catch (Exception ex) { CommonInfo.Output("WS返回给客户端异常:{0}", ex.Message); } }
/// <summary> /// 新消息 /// </summary> /// <param name="e"></param> protected override void OnMessage(WebSocketSharp.MessageEventArgs e) { try { LastRecvTime = DateTime.Now; if (e.IsText) { switch (e.Data) { case "HeartBeat": this.Send(Newtonsoft.Json.JsonConvert.SerializeObject(new WSResModel(ResCode.HeartBeatRes))); return; case "TaskIsExist": if (HandlerTaskManager.ContainsTask(this.TaskId)) { this.Send(Newtonsoft.Json.JsonConvert.SerializeObject(new WSResModel(ResCode.Wait))); } else { SendAndClose(new WSResModel(ResCode.Err, "任务不存在!")); } return; } } BaseHandler handler = HandlerManager.CreateHandler(PathName); if (handler == null) { SendAndClose(new WSResModel(ResCode.Err, string.Format("请求路径{0}未找到对应Handler", PathName))); return; } handler.Path = this.PathName; handler.TaskId = this.TaskId; handler.ReqIsWebSocket = true; handler.InPara = e.Data; //添加任务并执行 if (HandlerTaskManager.AddTask(handler)) { ThreadPool.QueueUserWorkItem((state) => { BaseHandler bh = state as BaseHandler; try { bh.HandlerTask(bh.InPara); } catch (Exception ex) { bh.ReturnToClient(new WSResModel(ResCode.Err, ex.Message)); } }, handler); } } catch (Exception ex) { CommonInfo.Output("WS处理消息异常:{0}", ex.Message); SendAndClose(new WSResModel(ResCode.Err, string.Format("服务器WS处理消息异常", ex.Message))); } }
/// <summary> /// 错误 /// </summary> /// <param name="e"></param> protected override void OnError(WebSocketSharp.ErrorEventArgs e) { if (e.Exception != null) { CommonInfo.Output("连接{0}错误:{1}", this.TaskId, e.Exception.GetBaseException().Message); } else { CommonInfo.Output("连接{0}错误:{1}", this.TaskId, e.Message); } }
/// <summary> /// 关闭客户端连接 /// </summary> /// <param name="session"></param> public void CloseClientSocket(MyWebSocketBehavior handler) { try { handler.Context.WebSocket.Close(); } catch (Exception ex) { CommonInfo.Output("断开客户端异常:{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> /// 定时清理未返回任务 /// </summary> public static void ClearTask() { try { List <BaseHandler> tempList = TaskQueue.Values.ToList(); foreach (BaseHandler item in tempList) { if (item.OutPara != null && item.ReturnTime != DateTime.MinValue && (DateTime.Now - item.ReturnTime).TotalSeconds > 20) { Remove(item.TaskId); } } } 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); } }
/// <summary> /// 后台线程方法 /// 主要处理客户端连接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DoWorkCheckMethod(object sender, DoWorkEventArgs e) { int timeout = HeartBeatSecond * 3;//连续3次检测无心跳 则表示客户端已死掉了 while (IsRunning) { try { _doWorkARE.Reset(); _doWorkARE.WaitOne(HeartBeatSecond); //定时清理任务 HandlerTaskManager.ClearTask(); foreach (WebSocketServiceHost host in _httpServer.WebSocketServices.Hosts) { List <IWebSocketSession> tempList = host.Sessions.Sessions.ToList(); foreach (var item in tempList) { MyWebSocketBehavior handler = item as MyWebSocketBehavior; if (handler != null) { //检测连接 if ((DateTime.Now - handler.LastRecvTime).TotalSeconds > timeout) { //断开客户端连接 CloseClientSocket(handler); } } } } } catch (Exception ex) { CommonInfo.Output("检测连接异常:{0}", ex.Message); } } }