《連載 | 物聯網框架ServerSuperIO教程》- 10.持續傳輸大塊資料流的兩種方式(如:檔案)
目 錄
10.持續傳輸大塊資料流的兩種方式(如:檔案)... 2
10.1 概述... 2
10.2 大塊資料流的兩種傳輸方式... 2
10.2.1 協議資料包的方式... 2
10.2.2 請求長度、確認的方式... 3
10.3 實現持續傳輸大塊資料... 4
10.3.1 設計請求傳送資料協議... 4
10.3.2 客戶端程式碼實現... 4
10.3.3 ServerSuperIO框架的實現及注意事項... 7
10.4 執行效果... 11
10.持續傳輸大塊資料流的兩種方式(如:檔案)
10.1 概述
以現在物聯網的現狀或是對物聯網的認知,特別是工業物聯網,必須具備整合多種資料來源的能力。資料來源大體分兩類:硬體產生和軟體產生。如下圖:
基於現實情況,作為物聯網框架必須具備各類資料的整合能力,以及各種應用場景。以資料大小為例,小到一次接收快取承載能力範圍內的資料,大到超出一次接收快取承載能力範圍的資料,只要網路允許,都有可能。以前的連載文章都是以小的資料包為基礎介紹的,這篇文章介紹大塊資料流的傳輸方式。
10.2 大塊資料流的兩種傳輸方式
10.2.1 協議資料包的方式
這種方式是規定好資料包協議的開頭和結尾,把大塊資料分解成一定長度的小資料包,以協議頭+小資料包+協議尾的組合方式分批次進行資料傳輸。接收到每個批次的資料後,再進行資料校驗,拼裝資料,還原出完整的資料。示意圖如下:
這種方式存在以下幾個問題:
(1) 每個包的資料出現問題後,要進行資料補發。要設計好協議,完成補發機制。
(2)資料來源是多種多樣的,例如:壓縮檔案、序列化的檔案、加密的檔案等等,那麼就存在每個小資料包的資料有可能會和協議頭或協議尾一致,甚至和CRC校驗一致的情況,從而導致資料無法正常校驗和解析,這時進行補發資料,可能出現同類情況是大概率事件。
選擇這種傳輸大塊資料流的方式,要根據現場的實際情況進行選擇,規避可能出現的風險,提高專案、產品整體的穩定性。
如果選擇這種方式,那麼根據前面介紹的文章,就可以實現,網友可以自己動手實現。這篇文章主要介紹下面這種方式。
10.2.2 請求長度、確認的方式
客戶端先發送請求傳送資料的命令,並且在命令標識本次要傳送資料的長度。如果服務端接收到該請求命令後,根據判斷請求資料長度是否在允許範圍內,然後返回相同命令資料或其他確認資料給客戶端,標識是否允許傳送該長度的資料資訊。如果可以傳送,那麼客戶端則持續傳送資料流,服務端也進行持續接收階段。示意圖如下:
針對這種資料傳輸的方式,ServerSuperIO專門提供了介面。下面進行詳細的介紹。
10.3 實現持續傳輸大塊資料
10.3.1 設計請求傳送資料協議
請求傳送0x62指令,共10個位元組,校驗和為從“從機地址”開始的累加和,不包括“資料報頭”、“校驗和”和“協議結束”。
請求指令資料幀如下:
服務端接收到該請求命令後,返回同樣的命令資訊給客戶端,客戶端則進入持續傳送資料的狀態。
10.3.2 客戶端程式碼實現
先發送請求資料命令,程式碼如下:
private void btSendFile_Click(object sender, EventArgs e) { try { if (this._tcpClient == null) { return; } if (!File.Exists(this.txtFilePath.Text)) { WriteLog("請選擇檔案"); return; } byte[] backData = new byte[10]; backData[0] = 0x55; backData[1] = 0xaa;//協議頭 backData[2] = byte.Parse(this.numericUpDown1.Value.ToString());//從機地址 backData[3] = 0x62;//命令 int count=(int)(new FileInfo(this.txtFilePath.Text)).Length; byte[] countBytes = BitConverter.GetBytes(count); backData[4] = countBytes[0]; backData[5] = countBytes[1]; backData[6] = countBytes[2]; backData[7] = countBytes[3]; byte[] checkSum = new byte[6]; Buffer.BlockCopy(backData, 2, checkSum, 0, checkSum.Length); backData[8] = (byte)checkSum.Sum(b => b);//計算校驗和 backData[9] = 0x0d; this._tcpClient.Client.Send(backData, 0, backData.Length, SocketFlags.None); } catch (SocketException ex) { Disconnect(); WriteLog(ex.Message); } }
接收到服務端的確認資訊後,持久傳送資料的程式碼如下:
private void SendFile() { FileStream fs = null; try { if (this._tcpClient == null) { return; } string fileName = this.txtFilePath.Text; if (!File.Exists(fileName)) { WriteLog("請選擇檔案"); return; } WriteLog("開始傳輸>>"); byte[] sendBuffer = new byte[1024]; fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); long length = fs.Length; int count = 0; Stopwatch watch = new Stopwatch(); watch.Start(); while (length > 0) { int sendNum = fs.Read(sendBuffer, 0, sendBuffer.Length); sendNum = _tcpClient.Client.Send(sendBuffer, 0, sendNum, SocketFlags.None); length -= sendNum; count += sendNum; float percent = ((fs.Length - length) / (float)fs.Length) * 100.0f; WriteLog("已傳:" + percent.ToString("0.00") + "%"); } watch.Stop(); WriteLog("傳輸完畢!總數:" + count.ToString() + ",耗時:" + watch.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture)); } catch (SocketException ex) { this.Disconnect(); WriteLog(ex.Message); } catch (Exception ex) { WriteLog(ex.Message); } finally { if (fs != null) { fs.Close(); fs.Dispose(); } } }
10.3.3 ServerSuperIO框架的實現及注意事項
客戶端的程式碼實現基本上沒有什麼好講的,主要是介紹基於ServerSuperIO框架,以裝置驅動的方式是怎麼實現的。注:以下自控模式實現。
- 1. 協議介面的實現
DeviceProtocol:ProtocolDriver介面有一個GetPackageLength(byte[] data, IChannel channel, ref int readTimeout)函式介面,data引數是請求傳送資料的命令,channel引數是當前IO通道的例項,readTimeout是自定義返回接收資料長度所要使用的時間,如果返回值為0的話,則認為不進入持續接收資料任務。可以通過channel引數直接返回確認資訊,具體程式碼如下:
public override int GetPackageLength(byte[] data, IChannel channel, ref int readTimeout) { if (data == null || data.Length <= 0) return 0; readTimeout = 2000; if (CheckData(data)) { try { if (data[3] == 0x62) //傳送檔案請求 { int length = BitConverter.ToInt32(new byte[] {data[4], data[5], data[6], data[7]}, 0); if (length <= 1024*1024) //限制 { int num = channel.Write(data); if (num > 0) { Console.WriteLine("返回檔案請求確認資料"); return length; } else { return 0; } } else { return 0; } } else { return 0; } } catch (Exception) { return 0; } } else { Console.WriteLine("校驗錯誤"); return 0; } }
2. 協議命令的實現
為了實現對大塊資料的處理,專門增加一個協議命令,用於解析、儲存資料。程式碼如下:
internal class DeviceFileCommand:ProtocolCommand { public override string Name { get { return CommandArray.FileData.ToString(); } } public override dynamic Analysis<T>(byte[] data, T t) { if (t != null) { string path = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt"; File.WriteAllBytes(path, t as byte[]); return path; } else { return null; } } }
- 3. 裝置驅動呼叫協議,並驅動協議命令
在接收大塊資料流的時候,會把所有資料資訊返回到裝置驅動的Communicate介面,其中info引數的Data是當前請求資料的命令,BigData就是持續接收資料的資訊,通過呼叫this.Protocol.DriverAnalysis協議介面驅動協議命令DeviceFileCommand。具體程式碼如下:
public override void Communicate(ServerSuperIO.Communicate.IRequestInfo info) { string hexs = BinaryUtil.ByteToHex(info.Data); OnDeviceRuningLog("接收>>" + hexs); byte[] cmds = this.Protocol.GetCommand(info.Data); CommandArray cr = (CommandArray)cmds[0]; dynamic obj = this.Protocol.DriverAnalysis<byte[]>(cr.ToString(), info.Data, info.BigData); if (obj != null) { if (cr == CommandArray.RealTimeData) { _deviceDyn.Dyn = (Dyn)obj; } else if (cr == CommandArray.FileData) { OnDeviceRuningLog("檔案儲存路徑:" + obj.ToString()); } } OnDeviceRuningLog("通訊正常"); }
- 4. 宿主程式服務例項配置注意事項
主要在配置引數中配置StartCheckPackageLength = true,在接資料的過程中會檢測相應裝置驅動的協議介面GetPackageLength。
static void Main(string[] args) { DeviceSelfDriver dev2 = new DeviceSelfDriver(); dev2.DeviceParameter.DeviceName = "網路裝置"; dev2.DeviceParameter.DeviceAddr = 1; dev2.DeviceParameter.DeviceID = "1"; dev2.DeviceDynamic.DeviceID = "1"; dev2.DeviceParameter.DeviceCode = "1"; dev2.DeviceParameter.NET.RemoteIP = "127.0.0.1"; dev2.DeviceParameter.NET.RemotePort = 9600; dev2.CommunicateType = CommunicateType.NET; dev2.Initialize("1"); IServer server = new ServerManager().CreateServer(new ServerConfig() { ServerName = "服務1", ComReadTimeout = 1000, ComWriteTimeout = 1000, NetReceiveTimeout = 1000, NetSendTimeout = 1000, ControlMode = ControlMode.Self, SocketMode = SocketMode.Tcp, StartReceiveDataFliter = true, ClearSocketSession = false, StartCheckPackageLength = true, CheckSameSocketSession = false, DeliveryMode = DeliveryMode.DeviceIP, }); server.AddDeviceCompleted += server_AddDeviceCompleted; server.DeleteDeviceCompleted+=server_DeleteDeviceCompleted; server.Start(); server.AddDevice(dev2); while ("exit" == Console.ReadLine()) { server.Stop(); } }
10.4 執行效果
圖片
視訊
物聯網&整合技術(.NET) QQ群:54256083