private void ModbusRtu_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { List <byte> recevideData = e.ReceiveData; this.canSendNextRequestCommandBytes = true; if (null != recevideData) { this.currentRecivedByteData = recevideData; DataAnalyzeMode dataAnalyzeMode = ModbusConfigService.GetCurrentDataAnalyzeMode(); AnalyzeRecivedDataReponse reponse = RecivedDataAnalyzer.AnalyzeRecivedData(dataAnalyzeMode, this.currentRequestByteData, this.currentRecivedByteData); if (reponse.ModbusReponseSuccess && reponse.AnalyzeRecivedDataSuccess) { ProcessRegisterValue(reponse.Registers, this.allDataPoints); } //if (reponse.DataPointType == DataPointType.WriteAndReadByFunNum01 // || reponse.DataPointType == DataPointType.WriteAndReadByFunNum03) //{ // //TODO:分析写寄存器接受侦 //} } }
private void SerialPort_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { byte[] recevideData = e.ReceiveData.ToArray(); string recevideDataHexString = StringHelper.ConverByteArrayToHexString(recevideData); this.Dispatcher.Invoke(new Action(() => { this.tbrecevideData.Text += recevideDataHexString + "\n"; })); }
private void modbusRTU_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { byte[] recevideData = e.ReceiveData.ToArray(); string recevideDataHexString = HexString.ByteArrayToHexString(recevideData); this.Dispatcher.Invoke(new Action(() => { this.tbrecevideData.Text += recevideDataHexString + "\n"; })); }
void conversationService_OnReceivePocketData(object sender, ReceiveDataEventArgs e, NetworkStream stream) { //如果收到 客户端的关机信号 则移除 var newrow = db.TPacketData.NewTPacketDataRow(); PacketHelper ph = new PacketHelper(e.Data); var clientid = ph.SenderID; AppendList(clientid); #region XXX switch (ph.CommandCode) { //客户端 关机 通知 case CommandCodeType.ClientNotifyToServerShutdown: RemoveList(clientid); break; //客户端 报警 通知 case CommandCodeType.ClientNotifyToServerAlarm: //在LED屏显示合适的信息 //播放声音文件 //显示日志里 SysLog(0, string.Format("收到未处理指令包:{0}", BitConverter.ToString(e.Data))); break; //客户端 检查是否在线 case CommandCodeType.ClientReplyOnline: AppendList(clientid); break; default: SysLog(0, string.Format("收到未处理指令包:{0}", BitConverter.ToString(e.Data))); break; } #endregion //newrow.AutoRowGUID newrow.ReveiveDateTime = DateTime.Now; newrow.SendDateTime = DateTime.Now; newrow.PacketData = BitConverter.ToString(e.Data); newrow.CommandCode = (short)ph.CommandCode; newrow.CommandPara = (short)ph.CommandPara; newrow.PacketType = (byte)ph.PacketType; newrow.SenderId = ph.SenderID; db.TPacketData.AddTPacketDataRow(newrow); new TPacketDataTableAdapter().Update(db.TPacketData); db.AcceptChanges(); }
private void SerialPort_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { List <byte> recevideData = e.ReceiveData; //this.canSendNextRequestCommandBytes = true; if (null != recevideData) { this.currentRecivedByteData = recevideData; } }
private void RaiseCurrentReceiveDataChangedEvent(List <byte> receiveData) { if (null != receiveData) { if (null != OnCurrentRequestDataChanged) { ReceiveDataEventArgs requstDataEventArgs = new ReceiveDataEventArgs(receiveData); foreach (EventHandler <ReceiveDataEventArgs> hanlder in OnCurrentReceiveDataChanged.GetInvocationList()) { hanlder(this, requstDataEventArgs); } } } }
private void SerialPort_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { List <byte> recevideData = e.ReceiveData; this.canSendNextRequestCommandBytes = true; if (null != recevideData) { this.currentRecivedByteData = recevideData; AnalyzeRecivedDataReponse reponse = ModbusRTU.AnalyzeRecivedDataStatic(this.dataAnalyzeMode, this.currentRequestByteData, recevideData); if (reponse.ModbusReponseSuccess && reponse.AnalyzeRecivedDataSuccess) { var dataPointsWhoseRealTimeDataChanged = ModbusRTU.SetDataPointValueFromRegisterValue(reponse.Registers, this.allDataPoints); } } }
private void _tcpConnection_OnDataReceived(object sender, ReceiveDataEventArgs e) { var bytes = e.Data.ToList(); Logger.Log("Data received: {0}", bytes); var command = _commandParser.Parse(bytes); if (command != null) { var response = _commandExecuter.Execute(command); if (response != null) { var data = _commandEncoder.Encode(response); _tcpConnection.Send(data); Logger.Log("Data sent: {0}", BitConverter.ToString(data)); } } }
private void ModbusRtu_OnReceiveDataChanged(object sender, ReceiveDataEventArgs e) { List <byte> recevideData = e.ReceiveData; if (null != recevideData) { this.currentRecivedByteData = recevideData; AnalyzeRecivedDataReponse reponse = AnalyzeRecivedData(this.currentRequestByteData, this.currentRequestByteData); ProcessRegisterValue(reponse.Registers, this.allDataPoints); //if (reponse.DataPointType == DataPointType.WriteAndReadByFunNum01 // || reponse.DataPointType == DataPointType.WriteAndReadByFunNum03) //{ // //TODO:分析写寄存器接受侦 //} } }
void client_OnReceiveEvent(object sender, ReceiveDataEventArgs args) { this.Invoke((MethodInvoker)(() => { ExchangeObject mObject = new ExchangeObject(); while (args.client.mBuffers.Count >= 12) { if (mObject.Format(args.client.mBuffers)) { switch ((Common.ECommand)mObject.PackType) { case Common.ECommand.Data: Data data = new Data(); if (mObject.GetStruct <Data>(ref data)) { toolStripStatusLabel1.Text = "收到"; textBox3.Text = Encoding.UTF8.GetString(data.Buffer); ObjectCount++; toolStripStatusLabel3.Text = "来自" + client.cSocket.LocalEndPoint.ToString() + "第" + ObjectCount + "个数据[" + data.DataGuid.ToString("N") + "]"; } else { Console.WriteLine("解析Data对象错误"); } break; case Common.ECommand.SocketInfo: SocketInformation mInfomation = Common.DeserializeSocketInfo(mObject.mData); CreateSocket(mInfomation); break; } } else { args.client.mBuffers.RemoveAt(0); } } })); }
void server_OnReceiveClientDataEvent(object sender, ReceiveDataEventArgs args) { ExchangeObject mObject = new ExchangeObject(); while (args.client.mBuffers.Count >= 12) { if (mObject.Format(args.client.mBuffers)) { switch ((Common.ECommand)mObject.PackType) { case Common.ECommand.Data: Data data = new Data(); if (mObject.GetStruct <Data>(ref data)) { if (data.Buffer != null) { byte[] dat = mObject.ToBuffer <Data>(data, Common.ECommand.Data); //(sender as SocketServer).SendData(args.client.SocketID, dat);//转发回给源客户端 long id = DataManager.AddData(args.client.sRemoteIPAndPort, data.Buffer); if (id == 0) { Logs.Create("记录中转数据到数据库失败!数据来源[" + args.client.sRemoteIPAndPort + "],数据为[" + Encoding.UTF8.GetString(data.Buffer) + "]"); } } } else { Console.WriteLine("解析Data对象错误"); Logs.Create("解析Data对象错误"); //(sender as SocketServer).CloseClient(args.client.SocketID); } break; case Common.ECommand.Login: int mProcessId = 0; if (mObject.GetStruct <int>(ref mProcessId)) { SetClientProcessId(args.client, mProcessId); //int port = Convert.ToInt32(args.client.sRemoteIPAndPort.Split(':')[1]); foreach (ClientSocket f in portMap.Keys) { foreach (ClientSocket t in portMap[f].Clients) { ExchangeTransfer(f, t); } } } else { Console.WriteLine("解析ProcessId对象错误"); Logs.Create("解析ProcessId对象错误"); //(sender as SocketServer).CloseClient(args.client.SocketID); } break; } } else { Console.WriteLine("对象错误" + args.client.mBuffers.Count.ToString()); args.client.mBuffers.RemoveAt(0); } } }
/// <summary> /// Retrieves URL into an Byte Array. /// </summary> /// <remarks>Fires the ReceiveData Event</remarks> /// <param name="Url">Url to read</param> /// <param name="BufferSize">Size of the buffer for each read. 0 = 8192</param> /// <returns></returns> public byte[] GetUrlBytes(string Url, long BufferSize) { HttpWebResponse Response = this.GetUrlResponse(Url); BinaryReader oHttpResponse = new BinaryReader(Response.GetResponseStream()); if (oHttpResponse == null) { return(null); } if (BufferSize < 1) { BufferSize = 8192; } long lnSize = BufferSize; if (Response.ContentLength > 0) { lnSize = this.oWebResponse.ContentLength; } else { lnSize = 0; } byte[] Result = new byte[lnSize]; byte[] lcTemp = new byte[BufferSize]; ReceiveDataEventArgs oArgs = new ReceiveDataEventArgs(); oArgs.TotalBytes = lnSize; lnSize = 1; int lnCount = 0; long lnTotalBytes = 0; while (lnSize > 0) { if (lnTotalBytes + BufferSize > this.oWebResponse.ContentLength) { BufferSize = this.oWebResponse.ContentLength - lnTotalBytes; } lnSize = oHttpResponse.Read(Result, (int)lnTotalBytes, (int)BufferSize); if (lnSize > 0) { lnCount++; lnTotalBytes += lnSize; // *** Raise an event if hooked up if (this.ReceiveData != null) { /// *** Update the event handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = null; // don't send anything here this.ReceiveData(this, oArgs); // *** Check for cancelled flag if (oArgs.Cancel) { this.bCancelled = true; goto CloseDown; } } } } // while CloseDown: oHttpResponse.Close(); // *** Send Done notification if (this.ReceiveData != null && !oArgs.Cancel) { // *** Update the event handler oArgs.Done = true; this.ReceiveData(this, oArgs); } return(Result); }
/// <summary> /// Retrieves the content of a Url into a string. /// </summary> /// <remarks>Fires the ReceiveData event</remarks> /// <param name="Url">Url to retrieve</param> /// <param name="BufferSize">Optional ReadBuffer Size</param> /// <returns></returns> public string GetUrl(string Url, long BufferSize) { StreamReader oHttpResponse = this.GetUrlStream(Url); if (oHttpResponse == null) { return(""); } long lnSize = BufferSize; if (this.oWebResponse.ContentLength > 0) { lnSize = this.oWebResponse.ContentLength; } else { lnSize = 0; } StringBuilder loWriter = new StringBuilder((int)lnSize); char[] lcTemp = new char[BufferSize]; ReceiveDataEventArgs oArgs = new ReceiveDataEventArgs(); oArgs.TotalBytes = lnSize; lnSize = 1; int lnCount = 0; long lnTotalBytes = 0; while (lnSize > 0) { lnSize = oHttpResponse.Read(lcTemp, 0, (int)BufferSize); if (lnSize > 0) { loWriter.Append(lcTemp, 0, (int)lnSize); lnCount++; lnTotalBytes += lnSize; // *** Raise an event if hooked up if (this.ReceiveData != null) { /// *** Update the event handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = lcTemp; this.ReceiveData(this, oArgs); // *** Check for cancelled flag if (oArgs.Cancel) { this.bCancelled = true; goto CloseDown; } } } // Thread.Sleep(1); // Give up a timeslice } // while CloseDown: oHttpResponse.Close(); // *** Send Done notification if (this.ReceiveData != null && !oArgs.Cancel) { // *** Update the event handler oArgs.Done = true; this.ReceiveData(this, oArgs); } return(loWriter.ToString()); }
/// <summary> /// Sends the Postbuffer to the server /// </summary> /// <param name="loPostData"></param> protected void StreamPostBuffer(Stream loPostData) { if (this.oPostStream.Length < this.BufferSize) { this.oPostStream.WriteTo(loPostData); // *** Handle Send Data Even // *** Here just let it know we're done if (this.SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = this.oPostStream.Length; Args.Done = true; this.SendData(this, Args); } } else { // *** Send data up in 8k blocks byte[] Buffer = this.oPostStream.GetBuffer(); int lnSent = 0; int lnToSend = (int)this.oPostStream.Length; int lnCurrent = 1; while (true) { if (lnToSend < 1 || lnCurrent < 1) { if (this.SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = lnSent; Args.TotalBytes = Buffer.Length; Args.Done = true; this.SendData(this, Args); } break; } lnCurrent = lnToSend; if (lnCurrent > this.BufferSize) { lnCurrent = BufferSize; lnToSend = lnToSend - lnCurrent; } else { lnToSend = lnToSend - lnCurrent; } loPostData.Write(Buffer, lnSent, lnCurrent); lnSent = lnSent + lnCurrent; if (this.SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = lnSent; Args.TotalBytes = Buffer.Length; if (Buffer.Length == lnSent) { Args.Done = true; this.SendData(this, Args); break; } this.SendData(this, Args); if (Args.Cancel) { this.Cancelled = true; break; } } } } }
void _mainClient_ReceiveDataChange(object sender, ReceiveDataEventArgs e) { try { JObject response = JObject.Parse(e.Data); if (response["type"] != null) { if (CleanJson(response["type"].ToString()) == "registered") { if (response["id"] != null) { if (CleanJson(response["id"].ToString()) == "register_0") { if (response["payload"]["client-key"] != null) { _clientKey = CleanJson(response["payload"]["client-key"].ToString()); using (StreamWriter writer = new StreamWriter(File.Create(_keyFilePath))) { writer.WriteLine(_clientKey); } _mainClient.SendData(_verifyClientKey()); } } else if (CleanJson(response["id"].ToString()) == "register_1") { CTimer waitToGetInfo = new CTimer(DisplayGetInfo, 2500); } } } else if (CleanJson(response["type"].ToString()) == "response") { if (response["id"] != null) { if (CleanJson(response["id"].ToString()) == "powerOff" && response["payload"] != null) { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { _mainClient.TemporaryDisconnect(); } } else if (CleanJson(response["id"].ToString()) == "getInputSocket") { _inputControls = new InputControls(_ipAddress, _port, CleanJson(response["payload"]["socketPath"].ToString())); _mainClient.SendData("{\"type\":\"request\",\"id\":\"getVolume\",\"uri\":\"ssap://audio/getVolume\"}"); } else if (CleanJson(response["id"].ToString()).Contains("changeInput_")) { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { _currentInput = CleanJson(response["id"].ToString()).Replace("changeInput_", string.Empty); if (onCurrentInputValue != null) { ExternalInput input = _externalInputs.Find(x => x.id == _currentInput); onCurrentInputValue(Convert.ToUInt16(_externalInputs.IndexOf(input))); } } } else if (CleanJson(response["id"].ToString()) == "getExternalInputs") { _externalInputs = JsonConvert.DeserializeObject <List <ExternalInput> >(response["payload"]["devices"].ToString()); List <string> inputNames = new List <string>(); List <string> inputIcons = new List <string>(); foreach (var input in _externalInputs) { inputNames.Add(input.label); inputIcons.Add(input.icon.Replace("http:", string.Format("http://{0}:{1}", _ipAddress, _port))); } if (onInputCount != null) { onInputCount(Convert.ToUInt16(_externalInputs.Count)); } if (onExternalInputNames != null) { foreach (var inputName in inputNames) { var encodedBytes = XSigHelpers.GetBytes(inputNames.IndexOf(inputName) + 1, inputName); onExternalInputNames(Encoding.GetEncoding(28591).GetString(encodedBytes, 0, encodedBytes.Length)); } } if (onExternalInputIcons != null) { foreach (var inputIcon in inputIcons) { var encodedBytes = XSigHelpers.GetBytes(inputIcons.IndexOf(inputIcon) + 1, inputIcon); onExternalInputIcons(Encoding.GetEncoding(28591).GetString(encodedBytes, 0, encodedBytes.Length)); } } } else if (CleanJson(response["id"].ToString()) == "getAllApps") { _apps = JsonConvert.DeserializeObject <List <App> >(response["payload"]["launchPoints"].ToString()); List <string> appNames = new List <string>(); List <string> appIcons = new List <string>(); foreach (var input in _apps) { appNames.Add(input.title); appIcons.Add(input.icon.Replace("http:", string.Format("http://{0}:{1}", _ipAddress, _port))); } if (onAppCount != null) { onAppCount(Convert.ToUInt16(_apps.Count)); } if (onAppNames != null) { foreach (var appName in appNames) { var encodedBytes = XSigHelpers.GetBytes(appNames.IndexOf(appName) + 1, appName); onAppNames(Encoding.GetEncoding(28591).GetString(encodedBytes, 0, encodedBytes.Length)); } } if (onAppIcons != null) { foreach (var appIcon in appIcons) { var encodedBytes = XSigHelpers.GetBytes(appIcons.IndexOf(appIcon) + 1, appIcon); onAppIcons(Encoding.GetEncoding(28591).GetString(encodedBytes, 0, encodedBytes.Length)); } } } else if (CleanJson(response["id"].ToString()) == "setVolume") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { _mainClient.SendData("{\"type\":\"request\",\"id\":\"getVolume\",\"uri\":\"ssap://audio/getVolume\"}"); } } else if (CleanJson(response["id"].ToString()) == "volumeUp") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { _mainClient.SendData("{\"type\":\"request\",\"id\":\"getVolume\",\"uri\":\"ssap://audio/getVolume\"}"); } } else if (CleanJson(response["id"].ToString()) == "volumeDown") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { _mainClient.SendData("{\"type\":\"request\",\"id\":\"getVolume\",\"uri\":\"ssap://audio/getVolume\"}"); } } else if (CleanJson(response["id"].ToString()) == "getVolume") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { var value = ScaleUp(Convert.ToInt16(CleanJson(response["payload"]["volume"].ToString()))); if (onVolumeValue != null) { onVolumeValue(Convert.ToUInt16(value)); } if (onVolumeMuteState != null) { if (CleanJson(response["payload"]["muted"].ToString()) == "true") { onVolumeMuteState(1); } else if (CleanJson(response["payload"]["muted"].ToString()) == "false") { onVolumeMuteState(0); } } } } else if (CleanJson(response["id"].ToString()) == "volumeMuteOn") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { if (onVolumeMuteState != null) { onVolumeMuteState(1); } } } else if (CleanJson(response["id"].ToString()) == "volumeMuteOff") { if (CleanJson(response["payload"]["returnValue"].ToString()) == "true") { if (onVolumeMuteState != null) { onVolumeMuteState(0); } } } } } } } catch (Exception ex) { if (_debugMode) { ErrorLog.Exception(string.Format("LgWebOs.Display._mainClient_ReceiveDataChange ID={0} Exeption Occured", _id), ex); } } }
/// <summary> /// Sends the Postbuffer to the server /// </summary> /// <param name="PostData"></param> protected void StreamPostBuffer(Stream PostData) { if ( _PostStream.Length < BufferSize) { _PostStream.WriteTo(PostData); // Handle Send Data Even // Here just let it know we're done if (SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = _PostStream.Length; Args.Done = true; SendData(this,Args); } } else { // Send data up in 8k blocks byte[] Buffer = _PostStream.GetBuffer(); int lnSent = 0; int lnToSend = (int) _PostStream.Length; int lnCurrent = 1; while (true) { if (lnToSend < 1 || lnCurrent < 1) { if (SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = lnSent; Args.TotalBytes = Buffer.Length; Args.Done = true; SendData(this,Args); } break; } lnCurrent = lnToSend; if (lnCurrent > BufferSize) { lnCurrent = BufferSize; lnToSend = lnToSend - lnCurrent; } else { lnToSend = lnToSend - lnCurrent; } PostData.Write(Buffer,lnSent,lnCurrent); lnSent = lnSent + lnCurrent; if (SendData != null) { ReceiveDataEventArgs Args = new ReceiveDataEventArgs(); Args.CurrentByteCount = lnSent; Args.TotalBytes = Buffer.Length; if (Buffer.Length == lnSent) { Args.Done = true; SendData(this,Args); break; } SendData(this,Args); if (Args.Cancel) { Cancelled = true; break; } } } } }
/// <summary> /// Retrieves URL into an Byte Array. /// </summary> /// <remarks>Fires the ReceiveData Event</remarks> /// <param name="url">Url to read</param> /// <param name="bufferSize">Size of the buffer for each read. 0 = 8192</param> /// <returns></returns> public async Task<byte[]> DownloadBytesAsync(string url, long bufferSize = 8192) { HttpWebResponse response = await DownloadResponseAsync(url); if (response == null) return null; long responseSize = bufferSize; if (response.ContentLength > 0) responseSize = _WebResponse.ContentLength; else // No content size provided responseSize = -1; Stream responseStream = response.GetResponseStream(); if (responseStream == null) { Error = true; ErrorMessage = "Failed to retrieve a response from " + url; return null; } if (response.ContentEncoding.ToLower().Contains("gzip")) { responseStream = new GZipStream(responseStream, CompressionMode.Decompress); responseSize = -1; // we don't have a size } else if (response.ContentEncoding.ToLower().Contains("deflate")) { responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); responseSize = -1; // we don't have a size } using (responseStream) { if (bufferSize < 1) bufferSize = 4096; var ms = new MemoryStream((int)bufferSize); byte[] buffer = new byte[bufferSize]; var args = new ReceiveDataEventArgs(); args.TotalBytes = responseSize; long bytesRead = 1; int count = 0; long totalBytes = 0; while (bytesRead > 0) { if (responseSize != -1 && totalBytes + bufferSize > responseSize) bufferSize = responseSize - totalBytes; bytesRead = await responseStream.ReadAsync(buffer, 0, (int)bufferSize); if (bytesRead > 0) { if (totalBytes == 0) HttpTimings.FirstByteTime = DateTime.UtcNow; // write to stream ms.Write(buffer, 0, (int)bytesRead); count++; totalBytes += bytesRead; // Raise an event if hooked up if (ReceiveData != null) { /// Update the event handler args.CurrentByteCount = totalBytes; args.NumberOfReads = count; args.CurrentChunk = null; // don't send anything here ReceiveData(this, args); // Check for cancelled flag if (args.Cancel) { _Cancelled = true; break; } } } } // while HttpTimings.LastByteTime = DateTime.UtcNow; // Send Done notification if (ReceiveData != null && !args.Cancel) { // Update the event handler args.Done = true; ReceiveData(this, args); } ms.Position = 0; var bytes = ms.ToArray(); ms.Dispose(); return bytes; } }
/// <summary> /// Retrieves URL into an Byte Array. /// </summary> /// <remarks>Fires the ReceiveData Event</remarks> /// <param name="Url">Url to read</param> /// <param name="BufferSize">Size of the buffer for each read. 0 = 8192</param> /// <returns></returns> public byte[] GetUrlBytes(string Url,long BufferSize) { HttpWebResponse Response = this.GetUrlResponse(Url); BinaryReader oHttpResponse = new BinaryReader(Response.GetResponseStream()); if (oHttpResponse == null) return null; if (BufferSize < 1) BufferSize = 8192; long lnSize = BufferSize; if (Response.ContentLength > 0) lnSize = this.oWebResponse.ContentLength; else lnSize = 0; byte[] Result = new byte[lnSize]; byte[] lcTemp = new byte[BufferSize]; ReceiveDataEventArgs oArgs = new ReceiveDataEventArgs(); oArgs.TotalBytes = lnSize; lnSize = 1; int lnCount = 0; long lnTotalBytes = 0; while (lnSize > 0) { if (lnTotalBytes + BufferSize > this.oWebResponse.ContentLength) BufferSize = this.oWebResponse.ContentLength - lnTotalBytes; lnSize = oHttpResponse.Read(Result,(int) lnTotalBytes,(int) BufferSize); if (lnSize > 0) { lnCount++; lnTotalBytes += lnSize; // *** Raise an event if hooked up if (this.ReceiveData != null) { /// *** Update the event handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = null; // don't send anything here this.ReceiveData(this,oArgs); // *** Check for cancelled flag if (oArgs.Cancel) { this.bCancelled = true; goto CloseDown; } } } } // while CloseDown: oHttpResponse.Close(); // *** Send Done notification if (this.ReceiveData != null && !oArgs.Cancel) { // *** Update the event handler oArgs.Done = true; this.ReceiveData(this,oArgs); } return Result; }
/// <summary> /// Retrieves URL into an Byte Array. /// </summary> /// <remarks>Fires the ReceiveData Event</remarks> /// <param name="url">Url to read</param> /// <param name="bufferSize">Size of the buffer for each read. 0 = 8192</param> /// <returns></returns> public byte[] DownloadBytes(string url, long bufferSize = 8192) { HttpWebResponse Response = DownloadResponse(url); if (Response == null) { return(null); } long responseSize = bufferSize; if (Response.ContentLength > 0) { responseSize = _WebResponse.ContentLength; } else { // No content size provided responseSize = -1; } Stream responseStream = null; if (Response.ContentEncoding.ToLower().Contains("gzip")) { responseStream = new GZipStream(Response.GetResponseStream(), CompressionMode.Decompress); responseSize = -1; // we don't have a size } else if (Response.ContentEncoding.ToLower().Contains("deflate")) { responseStream = new DeflateStream(Response.GetResponseStream(), CompressionMode.Decompress); responseSize = -1; // we don't have a size } else { responseStream = Response.GetResponseStream(); } BinaryReader responseReader = new BinaryReader(responseStream); //Response.GetResponseStream()); if (responseReader == null) { return(null); } if (bufferSize < 1) { bufferSize = 8192; } // pre-allocate the buffer MemoryStream ms = new MemoryStream(8192); byte[] buffer = new byte[bufferSize]; ReceiveDataEventArgs args = new ReceiveDataEventArgs(); args.TotalBytes = responseSize; long bytesRead = 1; int count = 0; long totalBytes = 0; while (bytesRead > 0) { if (responseSize != -1 && totalBytes + bufferSize > responseSize) { bufferSize = responseSize - totalBytes; } bytesRead = responseReader.Read(buffer, 0, (int)bufferSize); if (bytesRead > 0) { // write to stream ms.Write(buffer, 0, (int)bytesRead); count++; totalBytes += bytesRead; // Raise an event if hooked up if (ReceiveData != null) { /// Update the event handler args.CurrentByteCount = totalBytes; args.NumberOfReads = count; args.CurrentChunk = null; // don't send anything here ReceiveData(this, args); // Check for cancelled flag if (args.Cancel) { _Cancelled = true; goto CloseDown; } } } } // while CloseDown: responseReader.Close(); // Send Done notification if (ReceiveData != null && !args.Cancel) { // Update the event handler args.Done = true; ReceiveData(this, args); } //ms.Flush(); ms.Position = 0; return(ms.ToArray()); }
private void ReceiveUdpData(object sender, ReceiveDataEventArgs e) { string dat = e.recData; }
/// <summary> /// Retrieves the content of a Url into a string. /// </summary> /// <remarks>Fires the ReceiveData event</remarks> /// <param name="Url">Url to retrieve</param> /// <param name="BufferSize">Optional ReadBuffer Size</param> /// <returns></returns> public string GetUrl(string Url,long BufferSize) { StreamReader oHttpResponse = this.GetUrlStream(Url); if (oHttpResponse == null) return ""; long lnSize = BufferSize; if (this.oWebResponse.ContentLength > 0) lnSize = this.oWebResponse.ContentLength; else lnSize = 0; StringBuilder loWriter = new StringBuilder((int) lnSize); char[] lcTemp = new char[BufferSize]; ReceiveDataEventArgs oArgs = new ReceiveDataEventArgs(); oArgs.TotalBytes = lnSize; lnSize = 1; int lnCount = 0; long lnTotalBytes = 0; while (lnSize > 0) { lnSize = oHttpResponse.Read(lcTemp,0,(int) BufferSize); if (lnSize > 0) { loWriter.Append( lcTemp,0,(int) lnSize ); lnCount++; lnTotalBytes += lnSize; // *** Raise an event if hooked up if (this.ReceiveData != null) { /// *** Update the event handler oArgs.CurrentByteCount = lnTotalBytes; oArgs.NumberOfReads = lnCount; oArgs.CurrentChunk = lcTemp; this.ReceiveData(this,oArgs); // *** Check for cancelled flag if (oArgs.Cancel) { this.bCancelled = true; goto CloseDown; } } } // Thread.Sleep(1); // Give up a timeslice } // while CloseDown: oHttpResponse.Close(); // *** Send Done notification if (this.ReceiveData != null && !oArgs.Cancel) { // *** Update the event handler oArgs.Done = true; this.ReceiveData(this,oArgs); } return loWriter.ToString(); }
/// <summary> /// Retrieves URL into an Byte Array. /// </summary> /// <remarks>Fires the ReceiveData Event</remarks> /// <param name="url">Url to read</param> /// <param name="bufferSize">Size of the buffer for each read. 0 = 8192</param> /// <returns></returns> public byte[] DownloadBytes(string url, long bufferSize = 8192) { HttpWebResponse Response = DownloadResponse(url); if (Response == null) return null; BinaryReader responseReader = new BinaryReader(Response.GetResponseStream()); if (responseReader == null) return null; if (bufferSize < 1) bufferSize = 8192; long responseSize = bufferSize; if (Response.ContentLength > 0) responseSize = _WebResponse.ContentLength; else // No content size provided responseSize = -1; // pre-allocate the buffer MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[bufferSize]; ReceiveDataEventArgs args = new ReceiveDataEventArgs(); args.TotalBytes = responseSize; long bytesRead = 1; int count = 0; long totalBytes = 0; while (bytesRead > 0) { if (responseSize != -1 && totalBytes + bufferSize > responseSize) bufferSize = responseSize - totalBytes; bytesRead = responseReader.Read(buffer, 0, (int)bufferSize); if (bytesRead > 0) { // write to stream ms.Write(buffer, 0, (int)bytesRead); count++; totalBytes += bytesRead; // Raise an event if hooked up if (ReceiveData != null) { /// Update the event handler args.CurrentByteCount = totalBytes; args.NumberOfReads = count; args.CurrentChunk = null; // don't send anything here ReceiveData(this, args); // Check for cancelled flag if (args.Cancel) { _Cancelled = true; goto CloseDown; } } } else break; } // while CloseDown: responseReader.Close(); // Send Done notification if (ReceiveData != null && !args.Cancel) { // Update the event handler args.Done = true; ReceiveData(this, args); } //ms.Flush(); ms.Position = 0; return ms.ToArray(); }