private void ReadIncomingData(byte[] data) { var remainingDataLength = _buffer.Length - _receivedData; // we need to know if the incoming data is smaller than the needed data or not, if so we will read it all. int length = Math.Min(remainingDataLength, data.Length); // this mainly used to skip the header if (length != remainingDataLength) { length -= _readingOffset; } InternalRead(data, _buffer, length); _receivedData += length; if (_receivedData == _buffer.Length) { DataReceivedEvent?.Invoke(_buffer); if (CheckIfThereIsAnotherPacket(data)) { Reset(); _readingOffset += length; Read(data); } else { Reset(); } } // we don't want to reset the offset until we read the rest of the data * another packet * _readingOffset = 0; }
private void ParseFrame(NetworkDataEventArgs e) { var data = new List <byte>(); var payloadStartIndex = 2 + _parser.PayloadLenLenght + _parser.MaskingKeyLenght; switch ((WebSocketOpcode)_parser.Opcode) { case WebSocketOpcode.Ping: //Ping frame. Sent Pong Frame. _parser.PollReceived = true; data.AddRange(_parser.DataBuffer); data[0] = (byte)(data[0] & 0xF0); data[0] = (byte)(data[0] | (byte)WebSocketOpcode.Pong); Write(data.ToArray()); break; case WebSocketOpcode.Pong: _parser.PollReceived = true; break; case WebSocketOpcode.ConnectionClose: //Close frame. Sent Close back. var connectionCloseReason = (_parser.DataBuffer[payloadStartIndex] << 8) + ((int)_parser.DataBuffer[payloadStartIndex + 1] << 0); ConnectionCloseEvent?.Invoke(this, new ConnectionCloseEventArgs((ConnectionCloseReason)connectionCloseReason)); SendClose((ConnectionCloseReason)connectionCloseReason); break; case WebSocketOpcode.BinaryFrame: case WebSocketOpcode.TextFrame: DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs(e.LocalEndPoint, e.RemoteEndPoint, (WebSocketOpcode)_parser.Opcode, _parser.DataBuffer.GetRange(payloadStartIndex, _parser.PayloadLen).ToArray())); break; } }
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { List <byte> listBuffer = new List <byte>(); ReadBuffer(ref listBuffer); Thread.Sleep(50); //再次读取 ReadBuffer(ref listBuffer); if (listBuffer.Any()) { LogD.Info($"收到的原始报文:{ByteHelper.ToHexString(listBuffer.ToArray())}"); var requestInfo = SubstatonFilter.Filter(listBuffer); if (requestInfo == null) { IsBitError = true; } else { IsBitError = false; //触发事件 } _sendCommand.IsReceiveResponse = true; DataReceivedEvent?.Invoke(this, new ChannelDataEventArgs(_sendCommand, requestInfo)); } } catch (Exception ex) { _sendCommand.IsReceiveResponse = false; LogD.Error($"SerialPort_DataReceived:{ex}"); } }
// Event: Receiving Transponder data. Creates a list of tracks from it private void ReceiverOnTransponderDataReady(object sender, RawTransponderDataEventArgs e) { var tracks = new List <Track>(); // Add all tracks to list foreach (var data in e.TransponderData) { // Split data into separate strings string[] trackInfo = data.Split(';'); // Create DateTime object from trackInfo. int timeIndex = 4; string timeString = trackInfo[timeIndex].Substring(0, 4) + "-" + // 'yyyy' trackInfo[timeIndex].Substring(4, 2) + "-" + // 'mm' trackInfo[timeIndex].Substring(6, 2) + " " + // 'dd trackInfo[timeIndex].Substring(8, 2) + ":" + // 'hh' trackInfo[timeIndex].Substring(10, 2) + ":" + // 'mm' trackInfo[timeIndex].Substring(12, 2) + "," + // 'ss' trackInfo[timeIndex].Substring(14, 3); // 'fff' DateTime time = DateTime.ParseExact(timeString, "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture); // Create track from split data var t = new Track(trackInfo[0], int.Parse(trackInfo[1]), int.Parse(trackInfo[2]), int.Parse(trackInfo[3]), time, 0 , 0); //Velocity and compassCourse will be calculated in ATM // Add track to list tracks.Add(t); } DataReceivedEvent?.Invoke(this, new DataEventArgs(tracks)); }
/// <summary> /// Called when data is received. /// </summary> /// <param name="data">The data that was received.</param> /// <param name="offset">The offset.</param> /// <param name="count">The count.</param> protected async Task OnDataReceivedAsync(byte[] data, int offset, int count) { Logger.Debug($"Session {Id} read {count} bytes:"); Logger.Debug(Environment.NewLine + Utils.HexDump(data, offset, count)); // save it to the session read buffer await SessionReceiveBuffer.LockAsync().ConfigureAwait(false); try { await SessionReceiveBuffer.WriteAsync(data, offset, count).ConfigureAwait(false); // ensure we don't overflow our max buffer if (SessionReceiveBuffer.Length > MaxSessionReceiveBufferSize) { await ErrorAsync("Session buffer overflow!").ConfigureAwait(false); return; } } finally { SessionReceiveBuffer.Release(); } LastRecvTime = DateTime.Now; // push out a copy in the event byte[] dataCopy = new byte[count]; Array.Copy(data, offset, dataCopy, 0, count); DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs { Count = count, Data = dataCopy, } ); }
private void ProcessIncomingData() { while (_listeningAtcive) { var strChunk = _blockingCollection.Take(); DataReceivedEvent?.Invoke(this, new SerialDataEventArgs(strChunk)); } }
/// <summary> /// 事件传递函数 /// </summary> /// <param name="data"></param> protected virtual void OnDataReceived(TData data) { if (!Enable) { return; } DataReceivedEvent?.Invoke(data); }
private void TryBundleAccruedFrames() { if (accruedFrames.Count == 0) { return; } if (accruedFrames[0].Fin) { DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs { Opcode = accruedFrames[0].Opcode, UnmaskedApplicationData = accruedFrames[0].UnmaskedApplicationData }); accruedFrames.RemoveAt(0); if (accruedFrames.Count != 0) { TryBundleAccruedFrames(); } } else { var indexOfFinFrame = accruedFrames.FindIndex(frame => frame.Fin); if (indexOfFinFrame != -1) { var opcode = accruedFrames[0].Opcode; //CHECK: are these all the same var unmaskedApplicationData = new List <byte>(); for (var i = 0; i < indexOfFinFrame; i++) { unmaskedApplicationData.AddRange(accruedFrames[0].UnmaskedApplicationData); } for (var i = 0; i < indexOfFinFrame; i++) { accruedFrames.RemoveAt(0); } DataReceivedEvent?.Invoke(this, new DataReceivedEventArgs { Opcode = opcode, UnmaskedApplicationData = unmaskedApplicationData }); if (accruedFrames.Count != 0) { TryBundleAccruedFrames(); } } } }
public IEnumerator getDataRequest(string _email, string _password, DataReceivedEvent onUserData) { // Create a form object WWWForm form = new WWWForm(); form.AddField("email", _email); form.AddField("password", _password); form.AddField("action", "login"); // Create a download object WWW returned = new WWW(account_api, form); // Wait until the download is done yield return(returned); if (!string.IsNullOrEmpty(returned.error)) { Debug.Log("Error downloading: " + returned.error); yield break; } // Debug.Log(returned.text); NetworkResponse response = JsonUtility.FromJson <NetworkResponse>(returned.text); Dictionary <string, string> results = response.ToDictionary(); if (results["success"] == "true" && response.user != null) { Dictionary <string, string> userData = new Dictionary <string, string>(); int kills = 0; int deaths = 0; if (response.user.userdata.Length > 0) { UserInfo _userData = JsonUtility.FromJson <UserInfo>(response.user.userdata); kills = _userData.getKills(); deaths = _userData.getDeaths(); } userData["kills"] = kills.ToString(); userData["deaths"] = deaths.ToString(); onUserData.Invoke(userData); } }
protected virtual void OnDataReceivedEvent(AirplaneArgs e) { DataReceivedEvent?.Invoke(this, e); }
/// <summary> /// The crawl process. /// </summary> /// <param name="threadIndex"> /// The thread index. /// </param> private void CrawlProcess(object threadIndex) { var currentThreadIndex = (int) threadIndex; while (true) { // 根据队列中的 Url 数量和空闲线程的数量,判断线程是睡眠还是退出 if (UrlQueue.Instance.Count == 0) { _threadStatus[currentThreadIndex] = true; if (!_threadStatus.Any(t => t == false)) { break; } Thread.Sleep(2000); continue; } _threadStatus[currentThreadIndex] = false; if (UrlQueue.Instance.Count == 0) { continue; } var urlInfo = UrlQueue.Instance.DeQueue(); HttpWebRequest request = null; HttpWebResponse response = null; try { if (urlInfo == null) { continue; } // 1~5 秒随机间隔的自动限速 if (Settings.AutoSpeedLimit) { var span = _random.Next(1000, 5000); Thread.Sleep(span); } // 创建并配置Web请求 request = WebRequest.Create(urlInfo.UrlString) as HttpWebRequest; ConfigRequest(request); if (request != null) { response = request.GetResponse() as HttpWebResponse; } if (response != null) { PersistenceCookie(response); Stream stream = null; // 如果页面压缩,则解压数据流 if (response.ContentEncoding == "gzip") { var responseStream = response.GetResponseStream(); if (responseStream != null) { stream = new GZipStream(responseStream, CompressionMode.Decompress); } } else { stream = response.GetResponseStream(); } using (stream) { var html = ParseContent(stream, response.CharacterSet); ParseLinks(urlInfo, html); DataReceivedEvent?.Invoke( new DataReceivedEventArgs { Url = urlInfo.UrlString, Depth = urlInfo.Depth, Html = html }); stream?.Close(); } } } catch (Exception exception) { if (CrawlErrorEvent != null) { if (urlInfo != null) { CrawlErrorEvent( new CrawlErrorEventArgs {Url = urlInfo.UrlString, Exception = exception}); } } } finally { request?.Abort(); response?.Close(); } } }
private void InsertXmlString(List <DataToCollect> dataList, string filePath) { //create the xml XmlDocument fieldXmlDoc = new XmlDocument(); fieldXmlDoc.Load(filePath); //open the xml file foreach (DataToCollect myReading in dataList) { //build then data structure in xml XmlNode fieldDataNode = fieldXmlDoc.SelectSingleNode("FieldData"); XmlNode newDataNode = fieldXmlDoc.CreateNode(XmlNodeType.Element, "DataNode", null); XmlNode newFieldName = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Field", null); newDataNode.AppendChild(newFieldName); XmlText newFieldNameData = fieldXmlDoc.CreateTextNode(myReading.savedFieldName); newFieldName.AppendChild(newFieldNameData); XmlNode newLatReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Latitude", null); newDataNode.AppendChild(newLatReading); XmlText newLatData = fieldXmlDoc.CreateTextNode(myReading.savedLat.ToString()); newLatReading.AppendChild(newLatData); XmlNode newLongReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Longitude", null); newDataNode.AppendChild(newLongReading); XmlText newLongData = fieldXmlDoc.CreateTextNode(myReading.savedLon.ToString()); newLongReading.AppendChild(newLongData); XmlNode newAltReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Altitude", null); newDataNode.AppendChild(newAltReading); XmlText newAltData = fieldXmlDoc.CreateTextNode(myReading.savedAlt.ToString()); newAltReading.AppendChild(newAltData); XmlNode newSpeedReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Speed", null); newDataNode.AppendChild(newSpeedReading); XmlText newSpeedData = fieldXmlDoc.CreateTextNode(myReading.savedSpeedKph.ToString()); newSpeedReading.AppendChild(newSpeedData); XmlNode newYieldReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Yield", null); newDataNode.AppendChild(newYieldReading); XmlText newYieldData = fieldXmlDoc.CreateTextNode(myReading.savedYieldTime.ToString()); newYieldReading.AppendChild(newYieldData); XmlNode newPaddleReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Paddle", null); newDataNode.AppendChild(newPaddleReading); XmlText newPaddleData = fieldXmlDoc.CreateTextNode(myReading.savedPaddleTime.ToString()); newPaddleReading.AppendChild(newPaddleData); XmlNode newDate = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Date", null); newDataNode.AppendChild(newDate); XmlText newDateData = fieldXmlDoc.CreateTextNode(myReading.savedDate.ToString()); newDate.AppendChild(newDateData); XmlNode newTimeReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Time", null); newDataNode.AppendChild(newTimeReading); XmlText newTimeData = fieldXmlDoc.CreateTextNode(myReading.savedTime.ToString()); newTimeReading.AppendChild(newTimeData); fieldDataNode.AppendChild(newDataNode); } fieldXmlDoc.Save(filePath); //save record to xml file if (DataReceivedEvent != null) //do we have subscribers { SendDataStoredArgs args = new SendDataStoredArgs() { dataSaved = true }; DataReceivedEvent.Invoke(null, args); } }
/// <summary> /// ''' Polling is started in Initialize /// ''' </summary> private static void PollSerialPort() { try { byte[] Buffer; while (true) { if (Port.BytesToRead > 1) { Thread.Sleep(20); Buffer = new byte[Port.BytesToRead + 1]; Port.Read(Buffer, 0, Buffer.Length); char[] Chars = System.Text.Encoding.UTF8.GetChars(Buffer); for (var i = 0; i <= Chars.Length - 1; i++) { Data += Chars[i]; } switch (CurrentMode) { case (int)Mode.Connect: { // Get IP if (InString(Data, "+CIFSR:STAIP,")) { IPAddress = ParseIPAddres(Data); } break; } case (int)Mode.TCPServer: case (int)Mode.AP: { if (InString(Data, "+IPD")) { ServerRequest = Data; // Get the current connection linked ID // Used to send the requested data in SendServerRequest LinkedID = GetLinkID(ServerRequest); if (CurrentMode == (int)Mode.TCPServer) { ServerRequestEvent.Invoke(); } if (CurrentMode == (int)Mode.AP) { APServerRequestEvent.Invoke(); } } break; } case (int)Mode.TCPClient: { // Returned request from Google if (InString(Data, "+IPD")) { GetTimeFromString(Data); } break; } } DataReceivedEvent.Invoke(); Data = string.Empty; } Thread.Sleep(100); } } catch (Exception ex) { PrintData("Error: PollSerialPort: " + ex.ToString()); } }
private void RaiseDataReceived(ReceivedDataArgs _args) { DataReceivedEvent?.Invoke(this, _args); }
private void RaiseReceivedEvent(byte[] data, EndPoint source) { Logger.Log(LogLevel.Information, "Received data from {0}.", source.ToString()); DataReceivedEvent?.Invoke(this, data, source); }
/// <summary> /// Event delegate to notify state change events. /// </summary> /// <param name="args">Device event data.</param> protected void OnDataReceived(SesnsorReadEventArgs args) { DataReceivedEvent?.Invoke(this, args); }
private void OnDataReceivedEvent(byte[] data, IPEndPoint localEndPoint, IPEndPoint remoteEndPoint) { DataReceivedEvent?.Invoke(this, new NetworkDataEventArgs(data, localEndPoint, remoteEndPoint)); }
void DataReceived(byte[] data) { DataReceivedEvent?.Invoke(data); }