using GeneralLib; using NetLib; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace SunVoteARSPPT { public class VoteServer { private static NetServer NServer = null; public static Dictionary DicSessionName = null; public static Dictionary DicSessionNameNo = null; private static Dictionary DicSessionID = null; private static string PwdServer = ""; public static Dictionary>> DicRosterMeet = new Dictionary>>(); public static FrmServerSet FmServerSet = null; public static string KeyName = "Name"; public static string KeyPwd = "Pwd"; public static string KeyLogon = "KeyLogon"; public static string KeyStartVote = "StartVote"; public static string KeySendType = "SendType"; /// /// 程序启动时调用一次 /// public static void ServerInit() { NServer = new NetServer(); DicSessionName = new Dictionary(); DicSessionNameNo = new Dictionary(); DicSessionID = new Dictionary(); NServer.SessionConnected += NServer_SessionConnected; NServer.SessionClosed += NServer_SessionClosed; NServer.MessageReceived += NServer_MessageReceived; NServer.DataReceived += NServer_DataReceived; NServer.SessionErr += NServer_SessionErr; StartVote(false); TmrCheckOn = new System.Timers.Timer(); TmrCheckOn.Elapsed += TmrCheckOn_Elapsed; TmrCheckOn.Interval = 1000; TmrCheckOn.AutoReset = true; } public static bool IsStart { get { return NServer.IsStart; } } public static bool Start(int port, string pwd) { bool res = false; try { if (!NServer.Setup(port)) return false; PwdServer = pwd; res = NServer.Start(); AddLog("Server Start");//日志 TmrCheckOn.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex + ""); } return res; } public static void Stop() { TmrCheckOn.Enabled = false; AddLog("Server Stop");//日志 VoteServer.DicSessionID.Clear(); NServer.Stop(); Globals.SunVoteARSAddIn.PPTShow.StopTmrSendSlideScreen(); } public static void ShowServerSet() { if ((FmServerSet == null) || (FmServerSet.IsDisposed))//杨斌 2020-05-16 FmServerSet = new FrmServerSet(); FmServerSet.TopMost = true;//杨斌 2020-05-15 FmServerSet.Show();//杨斌 2020-05-15 } public static string GetDicDataPar(Dictionary dicData, string key) { string res = ""; if (dicData.ContainsKey(key)) res = dicData[key] + ""; return res; } public static string GetSessionPar(NetSession session, string key) { string res = ""; if (session.DicPar.ContainsKey(key)) res = session.DicPar[key]; return res; } private static void NServer_SessionConnected(NetSession session) { bool bePass = false; if (string.IsNullOrEmpty(PwdServer)) { bePass = true; } else { string pwd = GetSessionPar(session, KeyPwd); bePass = (pwd == PwdServer); } Dictionary dicSend = new Dictionary(); string msg = ""; AddLog("Session Connect", session);//日志 if (bePass) { string name = GetSessionPar(session, KeyName); if (name.Length > 0) { if (DicSessionName.ContainsKey(name)) { string oldID = DicSessionName[name].ID; if (oldID != session.ID)//不会碰到相同ID { if (DicSessionID.ContainsKey(oldID)) { AddLog("Session Already Logond Elsewhere", DicSessionName[name]); Dictionary dicSendOld = new Dictionary(); dicSendOld.Add(KeyLogon, "Already logond elsewhere!"); //dicSendOld.Add(KeyStartVote, GetVoteState()); GetVoteState(dicSendOld); msg = MyJson.Serialize(dicSendOld); NServer.Send(msg, oldID); NServer.CloseSession(oldID); } if (DicSessionID.ContainsKey(oldID)) DicSessionID.Remove(oldID); } DicSessionName[name] = session; dicSend.Add(KeyLogon, "OK"); //dicSend.Add(KeyStartVote, GetVoteState()); GetVoteState(dicSend); msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); AddLog("Session Connect OK", session); //if (Globals.SunVoteARSAddIn.PPTShow.IsShowSlide)//杨斌 2019-05-10 //{ // SendVoteData(session); //} } else { DicSessionName.Add(name, session); DicSessionNameNo.Add(name, DicSessionName.Count); dicSend.Add(KeyLogon, "OK"); //dicSend.Add(KeyStartVote, GetVoteState()); GetVoteState(dicSend); msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); AddLog("Session Connect OK", session); //if (Globals.SunVoteARSAddIn.PPTShow.IsShowSlide)//杨斌 2019-05-10 //{ // SendVoteData(session); //} } DicSessionID.Add(session.ID, session);//不会碰到相同ID SessionChange(session); DicLastMsg[session.ID] = DateTime.Now;//杨斌 2020-05-18 } else//客户端控制,不会碰到空名字 { AddLog("Session Name is Empty", session); dicSend.Add(KeyLogon, "The name can not be empty!"); msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); NServer.CloseSession(session.ID); } } else { AddLog("Session Wrong Password", session); dicSend.Add(KeyLogon, "Wrong Password!"); msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); NServer.CloseSession(session.ID); } } static List LstLog = new List(); internal static void AddLog(string info, NetSession session = null) { try { info = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + info; if (session != null) { info += " " + GetSessionPar(session, KeyName) + " " + session.ID + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port; } LstLog.Add(info); if (TmrLog == null) { TmrLog = new System.Timers.Timer(); TmrLog.Elapsed += TmrLog_Elapsed; TmrLog.Interval = 10; TmrLog.AutoReset = false; } if (!TmrLog.Enabled) TmrLog.Enabled = true; } catch (Exception ex) { string sErr = ex + ""; //System.Windows.Forms.MessageBox.Show(ex + ""); } } static System.Timers.Timer TmrLog = null; static bool IsRunTimer = false; private static void TmrLog_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { if (IsRunTimer) { TmrLog.Enabled = true; return; } IsRunTimer = true; ////Delay(10000); try { TmrLog.Enabled = false; string file = AppDomain.CurrentDomain.BaseDirectory + "session-" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; while (LstLog.Count > 0) { string info = LstLog[0] + "\r\n"; LstLog.RemoveAt(0); System.IO.File.AppendAllText(file, info); } } catch (Exception ex) { string sErr = ex + ""; //System.Windows.Forms.MessageBox.Show(ex + ""); } IsRunTimer = false; } public static void Delay(long ms) { Stopwatch t = Stopwatch.StartNew(); while (t.ElapsedMilliseconds < ms) System.Windows.Forms.Application.DoEvents(); } public static bool IsOnline(NetSession session) { bool isOnline = DicSessionID.ContainsKey(session.ID); string name = GetSessionPar(session, KeyName); if (VoteServer.DicSessionName.ContainsKey(name)) isOnline = VoteServer.DicSessionID.ContainsKey(VoteServer.DicSessionName[name].ID); return isOnline; } private static void SessionChange(NetSession session) { bool isOnline = IsOnline(session); if ((FmServerSet != null) && (!FmServerSet.IsDisposed))//杨斌 2020-05-17 FmServerSet.SessionChange(session, isOnline); } private static string RosterMeetFile { get { return AppDomain.CurrentDomain.BaseDirectory + "RosterMeet.dat"; } } public static void SaveRosterMeet() { //if (DicRosterMeet.Count < 1) // return; if (DicRosterMeet == null) { LoadRosterMeet(); return; } string data = MyJson.Serialize(DicRosterMeet); System.IO.File.WriteAllText(RosterMeetFile, data); } public static void LoadRosterMeet() { if (System.IO.File.Exists(RosterMeetFile)) { string data = System.IO.File.ReadAllText(RosterMeetFile); DicRosterMeet = MyJson.DisSerialize>>>(data); } if (DicRosterMeet == null) DicRosterMeet = new Dictionary>>(); } public static void SendMsg(Dictionary data) { if (DicSessionID.Count < 1) return; string msg = MyJson.Serialize(data); NServer.Send(msg); } public static void ClearVote() { Dictionary dicSend = new Dictionary(); dicSend.Add("ClearVote", ""); SendMsg(dicSend); } /// /// 杨斌 2019-05-10 /// public static void SendVoteData() { foreach (var v in DicSessionName) { SendVoteData(v.Value); } } /// /// 杨斌 2019-05-10 /// public static void SendVoteData(NetSession session) { string meetName = GetSessionPar(session, KeyName); int meetNo = GetMeetNo(meetName); string meetNoStr = meetNo + "F"; Dictionary dicSend = new Dictionary(); string data = ""; List> lstData = new List>(); for (int i = 0; i < GlobalInfo.response.ResponseDataList.Count; i++) { var v = GlobalInfo.response.ResponseDataList[i]; if (v.KeyID.IndexOf(meetNoStr) == 0) { Dictionary dicData = new Dictionary(); dicData.Add("KeyID", v.KeyID); dicData.Add("KeyValue", v.KeyValue); dicData.Add("Speed", v.Speed); dicData.Add("Time", v.Time); lstData.Add(dicData); } } data = MyJson.Serialize(lstData); dicSend.Add("SendVoteData", ""); dicSend.Add("VoteData", data); string msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); } private static Dictionary DicVotePar = new Dictionary(); /// /// 模拟投票,测试用 /// public static void StartVote(bool isStart) { DicVotePar = new Dictionary(); int itemCount = 10; DicVotePar.Add("VoteType", "Choices"); DicVotePar.Add("ItemCount", itemCount);//专用来统计选项个数,比如图表刷新 if (isStart) { DicVotePar.Add(KeyStartVote, "Choices"); DicVotePar.Add("ChoicesCount", itemCount); DicVotePar.Add("ChoicesLimit", 1); DicVotePar.Add("OptionsMode", 0);//0ABC,1数字 DicVotePar.Add("ChoicesLessEnabled", 0); DicVotePar.Add("VoteModifyMode", 1); DicVotePar.Add("VoteSecrecyMode", 0); } else { DicVotePar.Add(KeyStartVote, "Stop"); } SendMsg(DicVotePar); } private static string GetVoteState(Dictionary dic)//2017-12-08有问题,ServerSet增加加载保存清除 { string voteType = "Stop"; if (DicVotePar.ContainsKey(KeyStartVote)) voteType = DicVotePar[KeyStartVote] + ""; foreach (var v in DicVotePar) { dic.Add(v.Key, v.Value); } return voteType; } public static void SendData(byte[] data, NetSession session = null) { if (session == null) NServer.Send(data); else NServer.Send(data, session.ID); } private static void NServer_SessionClosed(NetSession session, NetLib.CloseReason reason) { if (DicSessionID.ContainsKey(session.ID)) DicSessionID.Remove(session.ID); AddLog("Session Close", session);//日志 SessionChange(session); } static System.Timers.Timer TmrCheckOn = null;//杨斌 2020-05-17 static Dictionary DicLastMsg = new Dictionary();//杨斌 2020-05-17 private static void NServer_MessageReceived(NetSession session, string value) { //在ARS中解析:名单数据保存到库,按键数据到缓存 //if ((FmServerSet != null) && (!FmServerSet.IsDisposed))//杨斌 2020-05-17 // FmServerSet.ShowMsg(session, value); string meetName = GetSessionPar(session, KeyName); int meetNo = GetMeetNo(meetName); string meetNoStr = meetNo + "F"; Dictionary dic = MyJson.DisSerialize>(value); string sendType = GetDicDataPar(dic, KeySendType); if (sendType == "BeatHeart")//需回应。杨斌 2020-05-17 { Dictionary dicSend = new Dictionary(); dicSend.Add(KeySendType, "BeatHeartAck"); string msg = MyJson.Serialize(dicSend); NServer.Send(msg, session.ID); } if ((FmServerSet != null) && (!FmServerSet.IsDisposed))//杨斌 2020-05-17 FmServerSet.SessionChange(session, true); if (sendType == "SendRoster") { List> lsTable = new List>(); foreach (var v in dic) { if (v.Key != KeySendType) { lsTable.Add(MyJson.DisSerialize>(v.Value + "")); } } if (RosterList.RosterLoad == null) { RosterList.RosterLoad = new RosterList(); RosterList.RosterLoad.LoadRoster(); } if (lsTable.Count > 0) { RosterList.RosterLoad.RosterAddMeet(lsTable, meetNo + "", meetName); if ((FmServerSet != null) && (!FmServerSet.IsDisposed))//杨斌 2020-05-17 FmServerSet.ShowSessionRosterCount(meetName); } //杨斌 2019-05-14 //if (Globals.SunVoteARSAddIn.PPTShow.IsShowSlide)//杨斌 2019-05-10 SendVoteData(session); Globals.SunVoteARSAddIn.PPTShow.SendSlideScreen(null, session); } else if (sendType == "SendVote") { ResponsePar pa = new ResponsePar(); pa.KeyID = meetNoStr + GetDicDataPar(dic, "KeyID"); pa.KeyValue = GetDicDataPar(dic, "KeyValue"); pa.Speed = ConvertOper.Convert(GetDicDataPar(dic, "Speed")).ToDouble; DateTime time; if (DateTime.TryParse(GetDicDataPar(dic, "Time"), out time)) pa.Time = time; GlobalInfo.response.Busines_ResponseEventHander(pa); Globals.SunVoteARSAddIn.PPTShow.SendSlideScreenTimer();//杨斌 2017-12-10 //lblRefreshVoteStateButton.Text = (ConvertOper.Convert(lblRefreshVoteStateButton.Text).ToInt + 1) + ""; } DicLastMsg[session.ID] = DateTime.Now; } /// /// 杨斌 2020-05-18 /// private static void TmrCheckOn_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { foreach(var v in DicSessionID) { if (DicLastMsg.ContainsKey(v.Key)) { if ((DateTime.Now - DicLastMsg[v.Key]).TotalSeconds >= 2) { if ((FmServerSet != null) && (!FmServerSet.IsDisposed)) FmServerSet.SessionChange(v.Value, false); } } } } private static void NServer_DataReceived(NetSession session, byte[] value) { } /// /// 杨斌 2020-05-17 /// private static void NServer_SessionErr(NetSession session, Exception ex) { if ((FmServerSet != null) && (!FmServerSet.IsDisposed)) FmServerSet.SessionChange(session, false); } public static int GetMeetNo(string meetName) { int res = 0; if (DicSessionNameNo.ContainsKey(meetName)) res = DicSessionNameNo[meetName]; return res; } } }