/// <summary> /// 发送消息. /// </summary> /// <param name="myQQNumber">要发送消息的QQ.</param> /// <param name="friendUin">要接受消息的QQ的Uin</param> /// <param name="content">消息内容.</param> /// <returns></returns> public void SendMessage(string myQQNumber, string friendUin, string content) { // 2013-11-05 更新 // 新算法,为了保证发送内容的有序性,采用逐条消息发送. SendMsg sm = new SendMsg(friendUin, content); AddSendQueue(myQQNumber, sm); #region 原算法 // 原算法,不能保证内容的有序性 //Task<bool> tast = new Task<bool>(() => //{ // if (_QQMap.ContainsKey(myQQNumber)) // { // WebQQ qq = _QQMap[myQQNumber]; // Debug.WriteLine("{0} start Time:{1} content {2}",myQQNumber , DateTime.Now.ToString(),content ); // qq.SendMessage(friendUin, content, new Font("宋体", 12F), Color.Black); // Debug.WriteLine("{0} end Time:{1} content {2}", myQQNumber, DateTime.Now.ToString(), content); // } // return false; //} //); //tast.Start (); #endregion }
public static void Init() { JavaScriptSerializer serializer = JavaScriptSerializer.CreateInstance(); socket.On(Socket.EVENT_CONNECT, () => { IsConnected = true; Data data = new Data("server"); data.comefrom = "net"; socket.Emit("login", serializer.Serialize(data)); }); socket.On("postDataRequest", (data) => { HashObject hash = serializer.Deserialize <HashObject>(data.ToString()); SendMsg nmsg = new SendMsg("server"); nmsg.comefrom = "net"; nmsg.touid = hash.GetValue <string>("fuid"); ulong key = Cuid.NewCuid(); Counter counter = new Counter(); counter.All = hash.GetValue <ulong>("msg"); counter.Doned = 0; PostDataRequestList.Add(key, counter); nmsg.msg = key.ToString();//回传一个唯一标记 socket.Emit("postDataSure", serializer.Serialize(nmsg)); }); IsConnected = false; }
public int UpdateSendMsgById(int msgid, string replyContent, string replier, DateTime replyTime) { SendMsg sendMsg = sendMsgBLL.Get("MsgId", msgid); sendMsg.ReplyContent = replyContent; sendMsg.Replier = replier; sendMsg.ReplyTime = replyTime; sendMsg.Editor = UserCookies.AdminName; int count = sendMsgBLL.Update(sendMsg); //添加到收件箱表 ReceiveMsg receiveMsg = new ReceiveMsg(); receiveMsg.Content = sendMsg.ReplyContent; receiveMsg.SenderId = 0; receiveMsg.Sender = sendMsg.Replier; receiveMsg.ReceiverId = sendMsg.QuCustomerId; receiveMsg.Receiver = sendMsg.QuCustomerName; receiveMsg.CreaedTime = DateTime.Now; receiveMsg.SendTime = DateTime.Now; receiveMsg.MsgSource = 2; receiveMsg.MsgSourceId = sendMsg.MsgId; receiveMsg.ReplyQuestion = sendMsg.MsgContent; receiveMsg.Status = 1; receiveMsgBLL.Add(receiveMsg); return(count); }
/// <summary> /// /// </summary> /// <returns></returns> public ApiMessage <string> VerifyCode(string strPhone) { var api = new ApiMessage <string>() { Msg = "发送成功" }; var gCode = CacheHelper.GetCache("GCode_" + strPhone); if (gCode != null) { api.Success = false; api.Msg = "已经发送过验证码,不能重复获取"; return(api); } gCode = CacheHelper.GetCache("VCode_" + strPhone); if (gCode == null) { var random = new Random().Next(100000, 999999); CacheHelper.SetCache("VCode_" + strPhone, random.ToString(), new TimeSpan(0, 10, 0)); SendMsg.Send(strPhone, random.ToString()); } else { SendMsg.Send(strPhone, gCode.ToString()); } CacheHelper.SetCache("GCode_" + strPhone, strPhone, DateTime.Now.AddMinutes(3)); return(api); }
public ATM() { InitializeComponent(); sendMsg = new SendMsg(sendMsgNo);//call delegate dao.setConnect(); dao.InitListView(listView); }
public ActionResult SendMsg(SendMsg msg) { if (!ModelState.IsValid) { return(View(msg)); } string[] ids = msg.Ids.Split(new char[] { '|' }); Mesg mesg = new Mesg() { Title = msg.Title, Detail = msg.Detail, FromUID = User.Identity.GetUserId() }; ContextManger.Mesg.Add(mesg); foreach (string id in ids) { ApplicationUser user = UserManager.FindById(id); if (user != null) { MassMeg massMsg = new MassMeg() { NID = mesg.NID, ToUID = id, }; ContextManger.MassMeg.Add(massMsg); } } ContextManger.SaveChanges(); return(RedirectToAction("List", new { userType = msg.roleName })); }
private void OnImportComplete(SerializationCompletionReason completionReason, WorldAnchorTransferBatch deserializedTransferBatch) { if (completionReason != SerializationCompletionReason.Succeeded) { Debug.Log("Failed to import: " + completionReason.ToString()); if (retryCount > 0) { retryCount--; indicator.GetComponent <MeshRenderer>().material.color = Color.cyan; WorldAnchorTransferBatch.ImportAsync(anchorData, OnImportComplete); } return; } GameObject sr = GameObject.Find("RefernceSceneBuilder"); if (sr != null) { deserializedTransferBatch.LockObject("1_GC35L", sr); CompleteWaTime.text = Time.time.ToString(); SendMsg sendstr = new SendMsg("SyncPlantNum:" + IF.text); startSocketTime.text = Time.time.ToString(); tCP.SocketSendByte(sendstr); } else { Debug.Log("Failed to find object for anchor id: " + "1_GC35L"); indicator.GetComponent <MeshRenderer>().material.color = Color.red; } }
private void sendCallback(IAsyncResult asyncSend) { SendMsg sendBuff = asyncSend.AsyncState as SendMsg; socket.EndSend(asyncSend); if (this.netWorkState != NetWorkState.Running) { this._isSending = false; return; } lock (this._sendQueue) { if (this._sendQueue.Count == 0) { this._isSending = false; } else { sendBuff = this._sendQueue.Dequeue(); byte[] thisSend = sendBuff.GetSendBuff(); socket.BeginSend(thisSend, 0, thisSend.Length, SocketFlags.None, new AsyncCallback(sendCallback), sendBuff); } } }
public async Task <(bool, string)> Send(string ip, string lastIp) { SendMsg msg = new SendMsg(ConfigManager.Now.AppSettings.MessageApiConfig.URL, ConfigManager.Now.AppSettings.MessageApiConfig.AppKey); string msgContent = string.Format(ConfigManager.Now.AppSettings.MessageApiConfig.MessageTemplate, ip, lastIp); return(await msg.Send(msgContent, ConfigManager.Now.AppSettings.MessageApiConfig.Mobile)); }
// Use this for initialization async void Start() { Debug.Log("Waiting for a connection"); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; HostName IP = null; try { var icp = NetworkInformation.GetInternetConnectionProfile(); IP = Windows.Networking.Connectivity.NetworkInformation.GetHostNames().SingleOrDefault( hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); await socket.BindEndpointAsync(IP, port); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } var sendMsg = new SendMsg(); sendMsg.caller = TAG; sendMsg.seq = 0; sendMsg.data = "HoloLens UDP server started"; SendMessageObj(sendMsg); Debug.Log("Exit Start"); }
public JsonResult getSendMsggoById(int msgid, string MsgIds) { SendMsg sendMsg = sendMsgBLL.GetSendMsggoById(msgid, MsgIds); if (sendMsg != null) { sendMsg.Replier = "UP量化安全炒股卫士"; if (!string.IsNullOrEmpty(sendMsg.ReplyContent)) { sendMsg.ReplyTime = sendMsg.ReplyTime; } else { sendMsg.ReplyTime = DateTime.Now; } } JsonResult json = null; if (sendMsg != null) { json = new JsonResult(sendMsg); return(json); } else { return(null); } }
public override SendMsg MakeLogic() { var m = new SendMsg(); string[] cmdArray = { "[太阳]签到", "[太阳]签到排名", "[太阳]抽签", "[太阳]星座", "[太阳]今日运势", "[太阳]处女座今日运势", "[太阳]人品计算器张三", "[太阳]成语接龙", "[太阳]上海天气", "[太阳]快递单45689565", "[太阳]讲个笑话", "[太阳]3乘以12等于多少" }; var cmd = string.Empty; var me_nickName = base.Contact.GetNickName(base.Msg.To); foreach (var c in cmdArray) { cmd += c + "\r\n"; } m.type = 1; m.context = @"[玫瑰][玫瑰][玫瑰] 菜单 [玫瑰][玫瑰][玫瑰]\r\n菜单无需@\r\n其余口令需要AT" + me_nickName + "~~~~~~~~~~~~~~\r\n" + cmd + "~~~~~~~~~~~~~~\r\n以上展示部分口令\r\n机器人可以任意回答\r\n如果回答不匹配可以任意尝试"; return(m); }
public object GetData(int msgid, string paramslist) { SendMsgPageModel Model = new SendMsgPageModel(); SendMsg sendmsg = sendMsgBLL.GetSendMsgById(msgid); if (sendmsg != null) { if (sendmsg.ReplyContent != "") { Model.ViewText = "disabled='disabled'"; } sendmsg.Replier = "UP量化安全炒股卫士"; if (!string.IsNullOrEmpty(sendmsg.ReplyContent)) { sendmsg.ReplyTime = sendmsg.ReplyTime; } else { sendmsg.ReplyTime = DateTime.Now; } Model.SendMsg = sendmsg; Model.ParamsList = paramslist; //Model.TypeContent = TypeContent; //Model.MsgType = MsgType; //Model.TuTimeStart = TuTimeStart; //Model.TuTimeEnd = TuTimeEnd; //Model.ReplyTimeStart = ReplyTimeStart; //Model.ReplyTimeEnd = ReplyTimeEnd; //Model.YesOrNo = YesOrNo; //Model.Editor = Editor; } return(new PageResult(null, Model)); }
public override bool SendMessage(string word) { long time = Time.Now(); string url = WxApi.SendMessageUrl + "?sid=" + CurrentUser.WxSid + "&skey=" + CurrentUser.Skey + "&pass_ticket=" + CurrentUser.PassTicket + "&r=" + time; JObject jsonObj = new JObject(); jsonObj.Add("BaseRequest", JObject.FromObject(CurrentUser.BaseRequest)); SendMsg msg = new SendMsg(); msg.FromUserName = CurrentUser.Me.UserName; msg.ToUserName = user.UserName; msg.Type = 1; msg.Content = word; msg.ClientMsgId = time; msg.LocalID = time; TB_SendBox.Clear(); jsonObj.Add("Msg", JObject.FromObject(msg)); WxSendMsg wxsendmsg = HttpRequest.PostJsonSync <WxSendMsg>(url, jsonObj); TB_Receive.Text += "我:\n" + msg.Content + "\n"; return(true); }
private void NotifyIcon1_Click(object sender, System.EventArgs e) { ShowDetailMessage f = new ShowDetailMessage(); this.SendMessage += f.GetMessage; SendMessage(ListMessages.LastOrDefault().Title, ListMessages.LastOrDefault().Text, ConvertTo_PersianOREnglish_Date.GetPersianDate(ListMessages.LastOrDefault().DateSand)); f.ShowDialog(); }
public string CreateLimitSubscribeQRcode(int scene_id = 0) { if (scene_id == 0) { return("sceneid不能为0"); } return(SendMsg.CreateLimitSubscribeQRcode(scene_id)); }
public SendMsg MakeContent(WXMsg msg) { SendMsg m = new SendMsg(); m.type = 1; m.context = "云客服提醒:恭喜发财,红包拿来"; return(m); }
public void SPClientInit(SendMsg fMsg) { m_fSendMsg = fMsg; m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_bytes = new byte[BYTE_NUM]; }
/// <summary> /// 消息处理 /// </summary> /// <returns></returns> public static string MsgFeedback() { bool bGetFans = WeiXinTool.OpenIdToFans(WeiXinMsgInfo.OpenId); string[] aMPInfo = WeiXinTool.GetMPUserInfo(WeiXinMsgInfo.OriginalId); string[] aServerId = WeiXinTool.GetMPServerId(WeiXinMsgInfo.OriginalId); WeiXinBindInfo.MPUser = aMPInfo[0]; WeiXinBindInfo.MPPass = aMPInfo[1]; WeiXinLogin.ExecLogin(WeiXinBindInfo.MPUser, WeiXinBindInfo.MPPass); if (bGetFans) { foreach (string sServerId in aServerId) { if (sServerId == WeiXinFans.sFakeId) { return(ServerBack()); } } } if (aMPInfo == null) { return("客服系统配置出现问题,如果你是本系统管理员请进入后台完成相关设置。"); } WeiXinBindInfo.BreakMsg = Guid.NewGuid().ToString().Substring(0, 5); if (!bGetFans) { string sOutText = string.Format("您是首次使用“微客服”平台,将会为您自动注册到客服系统,如果在5秒内收到绑定成功信息则代表注册成功!<a href=\"http:////RMBZ.Net\\{0}\"> </a>", WeiXinBindInfo.BreakMsg); WritePage(sOutText, false); Thread.Sleep(2500); string[] aFakeId = Bind.MPBind.BindFakeId(WeiXinBindInfo.BreakMsg, WeiXinBindInfo.MPUser, WeiXinBindInfo.MPPass); if (aFakeId.Length == 2) { WeiXinFans.sFakeId = aFakeId[0]; string sSql = string.Format("INSERT INTO `mpserver_bridge` (`openid`, `fakeid`, `name`, `time`) VALUES ('{0}', '{1}', '{2}', '{3}')", WeiXinMsgInfo.OpenId, aFakeId[0], WeiXinTool.Base64Code(aFakeId[1]), DateTime.Now); CDBAccess.MySqlDt(sSql); SendMsg.SendMessageText(aFakeId[1] + " 绑定成功,现在您就可以和客服联系啦。", WeiXinFans.sFakeId); } else { //WriteFile.Write("log.txt", WeiXinMsgInfo.OpenId + ":NoFoundFakeId.\n"); } return("OK"); } else { if (aServerId == null) { return("无法联系到客服!\n\n本客服系统尚未设置客服人员ID,请管理员尽快设置!"); } else { string sServerId = aServerId[0]; string MsgText = string.Format("来自 {0} 的消息:\n\n{1}\n\n回复此消息请回复“{2}#回复内容”", WeiXinFans.sNickName, WeiXinMsgInfo.Text, WeiXinFans.sFansId); SendMsg.SendMessageText(MsgText, sServerId); return("消息已经送达至客服,我们会尽快为您做答复!\n回复“退出”可退出“微客服”平台。"); } } }
private string GetMessage(string user, string comefrom, string msg) { SendMsg cmsg = new SendMsg(user); cmsg.comefrom = comefrom; cmsg.msg = msg; cmsg.touid = user; return(JavaScriptSerializer.CreateInstance().Serialize(cmsg)); }
public ActionResult SendMsgTo() { //string mp3SavePth = System.Web.HttpContext.Current.Request.MapPath($"~/Upload/{DateTime.Now:yyyyMMddHHmmss}{Comm.Random.Next(1000, 9999)}.mp3"); //Comm.ConvertToMp3($"E:/201811271125152499.amr", mp3SavePth); SendMsg s = new SendMsg(); var resultstr = s.SendSMS("18820716886", "402477", "你好"); return(View()); }
public void SPConnInit(SendMsg fSAMsg) { m_socket = null; m_isUsed = false; m_bytes = new byte[BYTE_NUM]; m_byteCnt = 0; m_fSMsg = fSAMsg; }
//对特定客户端发送信息 public void DoSendToClient(object obj) { SendMsg sendMsg = (SendMsg)obj; if (sendMsg == null) { ServerLog.Instance.PrintError("SendMsg is null"); return; } if (sendMsg.Client == null) { ServerLog.Instance.PrintError("Client socket is null"); return; } if (!sendMsg.Client.Connected) { ServerLog.Instance.PrintError("Not connected to client socket"); sendMsg.Client.Close(); return; } try { DataStream bufferWriter = new DataStream(true); sendMsg.Req.Serialize(bufferWriter); byte[] msg = bufferWriter.ToByteArray(); byte[] buffer = new byte[msg.Length + 4]; DataStream writer = new DataStream(buffer, true); writer.WriteSInt32(msg.Length); //增加数据长度 writer.WriteRaw(msg); byte[] data = writer.ToByteArray(); IAsyncResult asyncSend = sendMsg.Client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), sendMsg.Client); bool success = asyncSend.AsyncWaitHandle.WaitOne(1000, true); if (!success) { ServerLog.Instance.PrintError("Send failed"); } string log = "SendTo clientId: " + sendMsg.ClientId + sendMsg.Req.DeserializeLog(); ServerLog.Instance.PrintSend(log); } catch (Exception e) { ServerLog.Instance.PrintError("Send Exception : " + e); } }
public AtmStates GetNext(SendMsg command) { var transition = new StateTransition(CurrentState, command); AtmStates nextState; if (!_transitions.TryGetValue(transition, out nextState)) { throw new CommunicationStateException("Incorrect State"); } return(nextState); }
public string CreateLimitSubscribeQRcodeByscene_str(string scene_str = "") { if (!string.IsNullOrEmpty(scene_str)) { return(SendMsg.CreateLimitSubscribeQRcode(scene_str)); } else { return("sceneid不能为0"); } }
//private readonly ILog _logger = LogManager.GetLogger(typeof(HelloJob)); //_logger.InfoFormat("HelloJob测试"); public void Execute(IJobExecutionContext context) { //MessageBox.Show("HelloJob"); try { SendMsg.SendLis(); } catch (Exception) { throw; } }
private async void WriteSendMsgAsync(string msg) { await Dispatcher.BeginInvoke(() => { if (SendMsg.LineCount > 100) { SendMsg.Clear(); } SendMsg.AppendText(msg + "\n"); SendMsg.ScrollToEnd(); }); }
private void SendMsgToNode(string text) { if (socket == null) { return; } SendMsg msg = new SendMsg(this.user); msg.touid = toUser; msg.msg = text; socket.Emit("sendMsg", JavaScriptSerializer.CreateInstance().Serialize(msg)); }
public void Execute(IJobExecutionContext context) { //MessageBox.Show("第二个任务"); //温湿度报警定时任务 try { SendMsg.SendJob(); } catch (Exception) { throw; } }
public SendMsg MakeContent(WXMsg msg) { WxContact contact = new WxContact(msg.Uin); //需要更新群内成员信息 var currMember = contact.GetOnLineGroupMember(msg.From); contact.Add(msg.From, currMember); //更新群内联系人信息 SendMsg m = new SendMsg(); m.context = "云客服提醒:呼呼,貌似有人退群了....."; m.type = 1; return(m); }
public LocalOutput(string SiteName, string FileName, string Header, SendMsg send_message) { this.send_message = send_message; this.SiteName = SiteName; this.Path = "Output/" + PNEToutputsites + "/" + SiteName + "/"; this.FileName = FileName; if (System.IO.File.Exists(Path + FileName)) { System.IO.File.Delete(Path + FileName); } if (System.IO.Directory.Exists(Path) == false) { System.IO.Directory.CreateDirectory(Path); } FileContent = new List<string>(new string[] { Header }); Write(); }
public void Send(Message_Upload msg) { //add it to the queue to send and let the send message thread take care of it. lock (MsgSeqLock) { //Get rid of any data on the queue that is older than one hour while (SendMsgQueue.Count > 0 && SendMsgQueue.Peek().MsgToSend.Age > 60000 * 60) { RemoveFromQueue(); } //queue it up. SendMsg myMsg = new SendMsg(); myMsg.Initialize(new MsgSendInfo(), msg); SendMsgQueue.Enqueue(myMsg); //Save it to a file, in case of power loss or program shuts down. SerializeQueueToXML(); } }
/// <summary> /// The thread that handles sending all messages. /// </summary> public void SendMessageThread() { while (mSendMessageThreadActive) { if (Connected == true) { try { //Get the next message if there is not a current one if (mCurrentMsgToSend == null && SendMsgQueue.Count > 0) { lock (MsgSeqLock) { mCurrentMsgToSend = SendMsgQueue.Peek(); } } else if (mCurrentMsgToSend == null) { //Is it time to send a keep alive? TimeSpan TimeSinceResponse = DateTime.Now.Subtract(mLastResponse); TimeSpan TimeSinceLastMsgSent = DateTime.Now.Subtract(mLastMsgSent); if ((TimeSinceResponse.TotalMilliseconds > (double)(iSleep * 1000)) && (TimeSinceLastMsgSent.TotalMilliseconds > (double)(iSleep * 1000))) { PFCSSendKeepAlive(); } } if (mCurrentMsgToSend != null) { bool blnSendItOut = false; //Send it out if it hasn't been sent out before if (mCurrentMsgToSend.SendInfo.LastSendTime == null) blnSendItOut = true; else { //Send it out again if a response has been received, but it was an error if (mCurrentMsgToSend.SendInfo.Response_Received == true && mCurrentMsgToSend.SendInfo.Response_Error != MessageErrors.ERR_NAK_A) { if (mCurrentMsgToSend.SendInfo.SendCount > miRetries) { lock (MsgSeqLock) { //Give up completely. //We receive 3 bad responses. Must be something wrong with the message. SendMsgQueue.Dequeue(); mCurrentMsgToSend = null; } } else blnSendItOut = true; } else if (mCurrentMsgToSend.SendInfo.Response_Received == true && mCurrentMsgToSend.SendInfo.Response_Error == MessageErrors.ERR_NAK_A && mCurrentMsgToSend.SendInfo.LastSendTime.Value.AddSeconds(miInterval) < DateTime.Now) { //For some reason, for a NAK-A response we treat it as if we send it again 5 seconds later, instead of immediately. //So don't set the Response Received for a NAK-A. Let the send message thread take care of automatic resend if (mCurrentMsgToSend.SendInfo.SendCount > miRetries) { lock (MsgSeqLock) { //Give up completely. //We receive 3 bad responses. Must be something wrong with the message. SendMsgQueue.Dequeue(); mCurrentMsgToSend = null; } } else blnSendItOut = true; } else if (mCurrentMsgToSend.SendInfo.LastSendTime.Value.AddSeconds(miInterval) < DateTime.Now) { //Send it out again if we haven't received a response yet. if (mCurrentMsgToSend.SendInfo.SendCount > miRetries) { lock (MsgSeqLock) { //Leave it on the queue, bur reset the send dates and counts mCurrentMsgToSend.SendInfo.SendCount = 0; mCurrentMsgToSend.SendInfo.FirstSendTime = null; mCurrentMsgToSend.SendInfo.LastSendTime = null; mCurrentMsgToSend.SendInfo.Response_Received = false; mCurrentMsgToSend.SendInfo.Response_Error = MessageErrors.ERR_NONE; mCurrentMsgToSend = null; } blnSendItOut = false; TCP_ErrorRecovery(); //Force a keep alive to send next lock (MsgSeqLock) { SendMsg myMsg = new SendMsg(); myMsg.Initialize(new MsgSendInfo(), KeepAliveMessage()); mCurrentMsgToSend = myMsg; } blnSendItOut = true; } else { blnSendItOut = true; } } } //Send the message if (blnSendItOut == true && mCurrentMsgToSend != null) { //Set the sequence number if its the first time sending the message // But don't set the sequence number for an ACK/NAK if (mCurrentMsgToSend.SendInfo.SendCount == 0) { if (mCurrentMsgToSend.MsgToSend.ResponseType == MessageResponseType.DataMessage) { if (mCurrentMsgToSend.MsgToSend.MsgType != MessageType.KeepAlive) { GetNextSeqNum(); } lock (MsgSeqLock) { mCurrentMsgToSend.MsgToSend.SequenceNum = LastMsgSeqNum; } } } //Update the send information, such as date/time,send count and set response received to false DateTime TimeSent = DateTime.Now; lock (MsgSeqLock) { mCurrentMsgToSend.SendInfo.LastSendTime = TimeSent; if (mCurrentMsgToSend.SendInfo.FirstSendTime == null) mCurrentMsgToSend.SendInfo.FirstSendTime = TimeSent; mCurrentMsgToSend.SendInfo.SendCount++; mCurrentMsgToSend.SendInfo.Response_Received = false; mCurrentMsgToSend.SendInfo.Response_Error = MessageErrors.ERR_NONE; } mLastMsgSent = DateTime.Now; Send(mCurrentMsgToSend.MsgToSend.ToByteArray()); if (MessageSent != null) MessageSent(this, new MessageReceivedEventArgs(mCurrentMsgToSend.MsgToSend)); if (mCurrentMsgToSend != null) { if (mCurrentMsgToSend.MsgToSend.ResponseType == MessageResponseType.ACK || mCurrentMsgToSend.MsgToSend.ResponseType == MessageResponseType.NAK) lock (MsgSeqLock) { if (SendMsgQueue.Count > 0 && mCurrentMsgToSend == SendMsgQueue.Peek()) RemoveFromQueue(); mCurrentMsgToSend = null; //don't wait for a response or resend an ACK or NAK. just remove it from the queue } } } } } catch (Exception ex) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, ex.ToString())); TCP_ErrorRecovery(); } } else //not connected { if (!Connected && PortType == PORT_TYPE.Soliciated && mBuffering == false) { SendMsgQueue.Clear(); if (mCurrentMsgToSend != null) { if (mCurrentMsgToSend.MsgToSend.MsgType == MessageType.SendingTestResults) mCurrentMsgToSend = null; } } } Thread.Sleep(100); } }
/// <summary> /// Save the queue to PFCS to a file. Only save msgs to the solicated port /// </summary> public void SerializeQueueToXML() { if (PortType == PORT_TYPE.Soliciated && mBuffering == true) { SendMsg[] sma; try { lock (MsgSeqLock) { string FileName = "QueuedMsgsToPFCS.xml"; sma = SendMsgQueue.ToArray(); //Cannot serialize a queue, so convert it to an array first. XmlSerializer serializer = new XmlSerializer(typeof(SendMsg[])); TextWriter textWriter = new StreamWriter(FileName); serializer.Serialize(textWriter, sma); textWriter.Close(); } } catch (Exception ex) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, ex.ToString())); } } else if (PortType == PORT_TYPE.Soliciated && mBuffering == false) { //Write a blank file if buffering is disabled SendMsg[] sma; try { lock (MsgSeqLock) { string FileName = "QueuedMsgsToPFCS.xml"; sma = new SendMsg[0]; //Cannot serialize a queue, so convert it to an array first. XmlSerializer serializer = new XmlSerializer(typeof(SendMsg[])); TextWriter textWriter = new StreamWriter(FileName); serializer.Serialize(textWriter, sma); textWriter.Close(); } } catch (Exception ex) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, ex.ToString())); } } }
Bot(StreamReader reader, StreamWriter writer, SendMsg join) { this.writer = writer; string line; CurrentThrottle = 1; CurrentLane = -1; send(join); while ((line = reader.ReadLine()) != null) { MsgWrapper msg = JsonConvert.DeserializeObject<MsgWrapper>(line); switch (msg.msgType) { case "carPositions": PositionObject pos = JsonConvert.DeserializeObject<PositionObject>(line); foreach (Datum testCar in pos.data) { if (testCar.id.name == Car.data.name) { Process(testCar); break; } } break; case "yourCar": Car = JsonConvert.DeserializeObject<CarObject>(line); break; case "gameInit": InitObject init = JsonConvert.DeserializeObject<InitObject>(line); Race = init.data.race; CalculateFastestRoute(); TrackLength = CalculateRouteLength(); break; case "gameEnd": Console.WriteLine("Race Over!"); break; case "gameStart": Console.WriteLine("Race Start!"); break; case "crash": CrashObject crash = JsonConvert.DeserializeObject<CrashObject>(line); Console.WriteLine("Crash {0}", crash.data.name); break; case "spawn": SpawnObject spawn = JsonConvert.DeserializeObject<SpawnObject>(line); Console.WriteLine("Spawn {0}", spawn.data.name); break; case "lapFinished": LapObject lap = JsonConvert.DeserializeObject<LapObject>(line); Console.WriteLine("Lap Complete {0} {1}", lap.data.car.name, (double)lap.data.lapTime.millis / 1000); break; case "joinRace": break; default: //Console.WriteLine(line); break; } Tick(); } }
private void send(SendMsg msg) { writer.WriteLine(msg.ToJson()); }
protected override void OnDataReceived(DataReceivedEventArgs e) { //base.OnSocketDataReceived(socket, e); try { Message_Upload message; //byte[] buffer = e.Packet.Buffer; //byte[] data = new byte[buffer.Length]; byte[] data = e.Data; if (e.Data.Length < 2) return; //Array.Copy(buffer, pos, data, 0, buffer.Length - pos - 1); if (!Message_Upload.TryParse(data, out message)) { if (MessageReceived != null) MessageReceived(this, new MessageReceivedEventArgs(message)); if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "Could not parse message. Starting Error Recovery.")); TCP_ErrorRecovery(); } else { //invalid message. don't worry about it. if (message.MachineID == "XXXX") return; mLastResponse = DateTime.Now; System.Diagnostics.Debug.Print("message.SequenceNum=" + message.SequenceNum.ToString() + "LastMsgSeqNum=" + LastMsgSeqNum.ToString()); if (message.ResponseType == MessageResponseType.DataMessage) { if (message.SequenceNum == 0) { //We must always accept a sequence number of 0. Reset our internal counter LastMsgSeqNum = 0; } else if (message.SequenceNum == LastMsgSeqNum && mLastDataMsgHadError == false) { if (LastMsgSeqNum != 0 && message.Error == MessageErrors.ERR_NONE) { //uh oh. dupicalte sequence number. Discard. message.Error = MessageErrors.ERR_ACK_D; } } else if (message.SequenceNum != LastMsgSeqNum + 1 && message.Error == MessageErrors.ERR_NONE) { //message out of sequence. Send PFCS the expected sequence number with a NAK-F. // PFCS should re-send the message with the expected sequence number taken from the NAK-F message // so set the sequence number of this message to the desired sequence number message.SequenceNum = LastMsgSeqNum + 1; message.Error = MessageErrors.ERR_NAK_F; } else if (message.Error == MessageErrors.ERR_NONE) { //Sequence number was good. LastMsgSeqNum = message.SequenceNum; } // // Change the error code returned by parsing // if (message.Error == MessageErrors.ERR_UNRECOG_CHAR) { message.Error = MessageErrors.ERR_NAK_A; } // // Check to see if this message has an error in it. Used only for allowing for duplicate sequence numbers. // if (message.Error == MessageErrors.ERR_NAK_A || message.Error == MessageErrors.ERR_NAK_J || message.Error == MessageErrors.ERR_NAK_H || message.Error == MessageErrors.ERR_NAK_I) mLastDataMsgHadError = true; else mLastDataMsgHadError = false; } else //its an ack or a nak { if (message.Error == MessageErrors.ERR_NONE || message.Error == MessageErrors.ERR_ACK_D) { if (mCurrentMsgToSend != null) { if (mCurrentMsgToSend.MsgToSend.SequenceNum == message.SequenceNum && mCurrentMsgToSend.MsgToSend.MsgType == message.MsgType) { //Received a valid ack or NAK and no error message lock (CurrMsgLock) { if (SendMsgQueue.Count > 0 && mCurrentMsgToSend == SendMsgQueue.Peek()) RemoveFromQueue(); mCurrentMsgToSend = null; } } } if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.SuccessfulMessage, "Connected. Successful Message.")); } else { //////////////////////////////////////////////////////////////////// ///Error Handling for ACK / NAK message received with an error code //////////////////////////////////////////////////////////////////// if (mCurrentMsgToSend != null) { if (mCurrentMsgToSend.MsgToSend.SequenceNum == message.SequenceNum && mCurrentMsgToSend.MsgToSend.MsgType == message.MsgType) { //Received a valid ack or NAK with an error message lock (CurrMsgLock) { mCurrentMsgToSend.SendInfo.Response_Received = true; mCurrentMsgToSend.SendInfo.Response_Error = message.Error; } } } switch (message.Error) { case MessageErrors.ERR_UNRECOG_CHAR: if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_UNRECOG_CHAR. Performing error recovery...")); message.Error = MessageErrors.ERR_NAK_A; //TCP_ErrorRecovery(); break; case MessageErrors.ERR_NAK_A: //Bad data received from PFD, message type not congigured in PFCS or data cannot be processed by PFCS // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_A - Bad data received from PFD, message type not congigured in PFCS or data cannot be processed by PFCS")); break; case MessageErrors.ERR_NAK_B: //Machine ID not valid. //it says to request the machine id but we are going to ignore this error message since we are assigned a static one. // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_B - MachineID not valid")); break; case MessageErrors.ERR_NAK_E: //sequence number not numeric // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above LastMsgSeqNum = 1; if (mCurrentMsgToSend != null) mCurrentMsgToSend.MsgToSend.SequenceNum = 1; if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_E - sequence number not numeric")); break; case MessageErrors.ERR_NAK_H: //Invalid message type. //Correct message type and resend //Error should never happen b/c we are doing error checking to prevent this from happening. // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_J - Invalid byte count of data")); break; case MessageErrors.ERR_NAK_J: //Invalid byte count of data, must be in the range 0000-1024 //Correct data length and resend //I guess it could be the msg was corrupted over the line. // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_J - Invalid byte count of data")); break; case MessageErrors.ERR_NAK_I: //Input exceeds 1024 bytes. //Reformat the message and resend //If we received this error, I have no idea what happened because we are checking for data > 1024. //I guess it could be the msg was corrupted over the line. // Set Response_Received to trye and let the SendMsgThread handle an automatic resend. Handled in if statement above if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, "ERR_NAK_I - Input exceeds 1024 bytes")); break; case MessageErrors.ERR_ACK_D: //Duplicate message sequence number //Process like ACK. Go to the next message. if (mCurrentMsgToSend != null) { lock (MsgSeqLock) { if (SendMsgQueue.Count > 0 && mCurrentMsgToSend == SendMsgQueue.Peek()) RemoveFromQueue(); mCurrentMsgToSend = null; } } break; } } } } if (MessageReceived != null) MessageReceived(this, new MessageReceivedEventArgs(message)); } catch (Exception ex) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, ex.ToString())); } }
private void CheckConnectionThread() { bool lastConnectState = false; DateTime lastConnectionTry; DateTime.TryParse("1/1/2000", out lastConnectionTry); while (mConnectionThreadActive) { try { //Raise connected event if connected state changed. Need to check before and after the connection section to make sure event gets raised. if (lastConnectState != Connected) { lastConnectState = Connected; DateTime.TryParse("1/1/2000", out mLastResponse); DateTime.TryParse("1/1/2000", out mLastMsgSent); if (lastConnectState == true) { mLastResponse = DateTime.Now; lastConnectionTry = DateTime.Now; if (mCurrentMsgToSend == null) { //Force a keep alive to send next lock (MsgSeqLock) { SendMsg myMsg = new SendMsg(); myMsg.Initialize(new MsgSendInfo(), KeepAliveMessage()); mCurrentMsgToSend = myMsg; } } if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Connected, "Connected")); } else { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Disconnected, "Disconnected")); //Clear the send dates and counts for the current message lock (CurrMsgLock) { if (mCurrentMsgToSend != null) { mCurrentMsgToSend.SendInfo.SendCount = 0; mCurrentMsgToSend.SendInfo.FirstSendTime = null; mCurrentMsgToSend.SendInfo.LastSendTime = null; mCurrentMsgToSend.SendInfo.Response_Received = false; mCurrentMsgToSend.SendInfo.Response_Error = MessageErrors.ERR_NONE; } } } } TimeSpan ts_LastConnectionTry = DateTime.Now - lastConnectionTry; TimeSpan ts_LastResponse = DateTime.Now - mLastResponse; if (!Connected && mblnOKToConnect) { if (ts_LastConnectionTry.TotalMilliseconds > miConnect * 1000) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.TryingToConnect, "Trying to connect...")); base.Connect(); lastConnectionTry = DateTime.Now; } } else if (ts_LastResponse.TotalMilliseconds > miSleep * 1000 * 2) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Disconnecting, "Disconnecting...")); base.Disconnect(); ClearBuffers(); } else if (mblnOKToConnect == false) { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Disconnecting, "Disconnecting...")); base.Disconnect(); ClearBuffers(); } //Raise connected event if connected state changed. Need to check before and after the connection section to make sure event gets raised. if (lastConnectState != Connected) { lastConnectState = Connected; DateTime.TryParse("1/1/2000", out mLastMsgSent); DateTime.TryParse("1/1/2000", out mLastResponse); if (lastConnectState == true) { mLastResponse = DateTime.Now; lastConnectionTry = DateTime.Now; if (mCurrentMsgToSend == null) { //Force a keep alive to send next lock (MsgSeqLock) { SendMsg myMsg = new SendMsg(); myMsg.Initialize(new MsgSendInfo(), KeepAliveMessage()); mCurrentMsgToSend = myMsg; } } if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Connected, "Connected")); } else { if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.Disconnected, "Disconnected")); //Clear the send dates and counts for the current message lock (CurrMsgLock) { if (mCurrentMsgToSend != null) { mCurrentMsgToSend.SendInfo.SendCount = 0; mCurrentMsgToSend.SendInfo.FirstSendTime = null; mCurrentMsgToSend.SendInfo.LastSendTime = null; mCurrentMsgToSend.SendInfo.Response_Received = false; mCurrentMsgToSend.SendInfo.Response_Error = MessageErrors.ERR_NONE; } } } } Thread.Sleep(1000); } catch(Exception ex) { if (mConnectionThreadActive == true) if (StateChanged != null) StateChanged(this, new StateChangeEventArgs(StateChange.ErrorHappened, ex.ToString())); } } }