




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、三個類,TcpCommon 主要實現了,發送接收消息,和文件hash的計算_blockLength =500 *1024string FilePath)new MD5CryptoServiceProvid【背景】最近做了一個雙機備份,就是服務器上有個文件夾,會接收客戶端傳來的文件,而我們要 做的就是同步這臺服務器和另一臺備用服務器上的文件為了實現這個功能我們使用的 tcp點對點傳輸.【開發環境】VS2005【實現原理】要實現同步要解決兩個問題,一個是獲取本地服務器上上傳上來的文件,二是實現兩臺機器間的文件傳輸.第一個問題我們用的 FileSystemWatcher這個可以監視指定文件夾下的文件
2、變動,然后我們把變動的文件信息記錄到數據庫,在指定的時間間隔后同步兩臺機器的文件.第二個問題我們用的tcp文件傳輸,我們按照一定的原則通過傳輸消息來告知備份服務器的要傳輸的文件名稱和大小,然后傳輸文件.【代碼】1:FileSystemWatcher監視文件變動的就不介紹了,很簡單的winform 控件應用.2:為了完成文件傳輸,我做了一個TcpHelper類庫,其中包括TcpCommon,TcpClientHelper,TcpListenerHelper文件傳輸時用的一些公共的方法比如發送接收文件TcpCommon甌using System;using System.Collections.G
3、eneric;using System.Text;using System.Security.Cryptography;using System.IO;using System.Net.Sockets;namespace Xpwy.Backup.PTcpHelperinternal class TcpCommonprivate staticreadonly int/ summary/計算文件的hash值/ </summary>internal string CalcFileHash(MD5CryptoServiceProvider md5 = er();byte 口 hash;us
4、ing (FileStream fs =new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read,4096 ) hash = md5.ComputeHash(fs); return BitConverter.ToString(hash); / summary / 發送文件 / /summary /param name="filePath"></param>/<param name="stream"></param>/<re
5、turns></returns>internalbool SendFile( string filePath, Networkstream stream) FileStream fs = File.Open(filePath, FileMode.Open); int readLength =0;/發送大小byte 口 length =BitConverter.GetBytes(To(length, 0);stream.Write(length,byte 口 data = new byte _blockLength;new byte 8;new FileInfo(filePat
6、h).Length).Copy0, 8);0)/發送文件while (readLength = fs.Read(data,0, _blockLength) >stream.Write(data,0, readLength); fs.Close(); return true ; / summary/接收文件/ </summary>/<param name="filePath">/param>/<param name="stream">/param>/ returns>/returns>int
7、ernal bool ReceiveFile(string filePath, Networkstream stream) trylong count = GetSize(stream); if (count =0) return false ;long index =0;byte 口 clientData =new byte _blockLength;if (File.Exists(filePath)File.Delete(filePath); string path= new FileInfo(filePath).Directory.FullName;if (!Directory.Exis
8、ts(path)Directory.CreateDirectory(path);FileStream fs = File.Open(filePath, FileMode.OpenOrCr eate);try/計算當前要讀取的塊的大小 int currentBlockLength =0;if (_blockLength < count - index) currentBlockLength = _blockLength;else currentBlockLength =(int )( count - index);int receivedBytesLen = stream.Read(cli
9、entData, 0, currentBlockLength);index += receivedBytesLen;fs.Write(clientData,0, receivedBytesLen);while (receivedBytesLen >0 && index < count) clientData =new byte _blockLength;receivedBytesLen =0;if (_blockLength < count - index)currentBlockLength = _blockLength; else currentBlock
10、Length = (int )(count - index); receivedBytesLen = stream.Read(clientData, 0, currentBlockLength);index += receivedBytesLen;fs.Write(clientData,0, receivedBytesLen); catch (Exception ex) return false ; finally fs.Close(); catch (Exception ex) return false ; return true ; / summary /發送消息/ /summary /p
11、aram name="message"></param>/<param name="stream"></param>/ <returns></returns>internal bool SendMessage(string message, Networkstream stream)byte 口 data = Encoding.UTF8.GetBytes(message);byte 口 resultData =new byte 8 + data.Length;BitConverter.Ge
12、tBytes(data.Length).CopyTo(resultData,0);data.CopyTo(resultData,8);stream.Write(resultData,0, resultData.Length);return true ; / summary/讀取消息/ /summary/ param name="stream"></param>/ <returns></returns> internal string ReadMessage(NetworkStream stream) string result =&
13、quot;"int messageLength =0;byte 口 resultbyte =new byte 500 *1024 ;/讀取數據大小 int index =0;int count = GetSize(stream);byte 口 data = new byte count;while (index < count && (messageLength = stream.Read(dat a, 0, count - index) !=0)data.CopyTo(resultbyte, index);index += messageLength;0, i
14、ndex);result = Encoding.UTF8.GetString(resultbyte, return result;/ <summary>/獲取要讀取的數據的大小/ </summary>/ <param name="stream"></param>/ <returns></returns> private int GetSize(NetworkStream stream) int count =0;byte 口 countBytes =new byte 8;try0, 8) =8)if (
15、stream.Read(countBytes,0);count = BitConverter.ToInt32(countBytes, else return 0; catch (Exception ex) return count; TcpClientHelper EH using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace Xpwy.Backup.PTcpHelper public class TcpClientHelper:IDisposab
16、le TcpClient client; NetworkStream netstream; string _serverip =""int _port =8080 ;TcpCommon tcpCommon =new TcpCommon();#region TcpClientHelper constructor public TcpClientHelper( string strServerIP, int serverPort) _serverip = strServerIP;_port = serverPort;#endregionpublic void
17、Start()client =new TcpClient(_serverip, _port);netstream = client.GetStream(); public void Stop() if (netstream != null ) netstream.Close(); if (client != null ) client.Close(); #region TcpCommon 所有方法public string CalcFileHash( string FilePath) return tcpCommon.CalcFileHash(FilePath);public bool Sen
18、dFile( string filePath) return tcpCommon.SendFile(filePath, netstream); public bool ReceiveFile( string filePath) return tcpCommon.ReceiveFile(filePath, netstream); public bool SendMessage( string message) return tcpCommon.SendMessage(message, netstream); public string ReadMessage()return tcpCommon.
19、ReadMessage(netstream);#endregion#region Disposable 成員public void Dispose。if (netstream != null )netstream.Close();if (client != null )client.Close();#endregionTcpListenerHelpersausing System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;using System.Th
20、reading;namespace Xpwy.Backup.PTcpHelperpublic class TcpListenerHelper""0;privatestring _strServerIP =privateint _serverPort =TcpListener server;TcpClient client;Networkstream netstream;lAsyncResult asyncResult;new TcpCommon();TcpCommon tcpCommon =ManualResetEvent listenConnected =new Manu
21、alResetEvent(false);bool _active = false ;public TcpListenerHelper(string strServerIP, int serverPort) _strServerIP = strServerIP;_serverPort = serverPort;server =new TcpListener(IPAddress.Parse(strServerIP), serverPort);server.Server.ReceiveTimeout =6000 ;server.Server.SendTimeout =6000 ;/ summary/
22、 啟動/ /summary public void Start() try _active =true ;server.Start(); catch (Exception ex) throw ex; / summary / 停止 / /summary public void Stop() try _active =false ;if (client != null ) client.Close();if (netstream !=null )netstream.Close(); server.Stop(); catch (Exception ex) throw ex;public void L
23、isten()new AsyncCallbalistenConnected.Reset();asyncResult = server.BeginAcceptTcpClient( ck(AsyncCall), server);public void AsyncCall(IAsyncResult ar) try TcpListener tlistener = (TcpListener)ar.AsyncState;if (_active) client = tlistener.EndAcceptTcpClient(ar); netstream = client.GetStream(); else c
24、lient =null ;netstream =null ;listenConnected.Set(); catch (Exception ex)throw ex;public bool WaitForConnect()listenConnected.WaitOne();if (client !=null && netstream !=nullelsereturn truereturn false#region TcpCommon 所有方法/ summary/計算文件的hash值/ /summarypublic string CalcFileHash( string FileP
25、ath)return tcpCommon.CalcFileHash(FilePath);/ summary/發送文件/ /summary/ <param name="filePath"/param/ returns/returnspublic bool SendFile( string filePath)return tcpCommon.SendFile(filePath, netstream);/ summary/接收文件/ /summary/ <param name="filePath"/param/ returns/returnspub
26、lic bool ReceiveFile( string filePath)return tcpCommon.ReceiveFile(filePath, netstream);/ summary/發送消息/ /summary/ param name="message"></param>/ <returns></returns>public bool SendMessage( string message) return tcpCommon.SendMessage(message, netstream); / summary/接收消息
27、/ /summary/ returns/returnspublic string ReadMessage() return tcpCommon.ReadMessage(netstream); #endregion#region IDisposable 成員public void Dispose。Stop(); #endregion 3:調用的代碼server 端:EEpublic void DoWork( object state)TcpListenerHelper tlistener = (TcpListenerHelper)state;tlistener.Listen();/ 監聽/等待知
28、道監聽到了連接while (tlistener.WaitForConnect()trystring firstMessage =""while (! string .IsNullOrEmpty(firstMessage = tlis tener.ReadMessage() if (firstMessage.ToLower() ="filebak" .ToLower()tlistener.SendMessage("filebakok" );#region 文件備份string filepath = Path.Combine(Enviro
29、nmen t.CurrentDirectory,"FileBak" + tlistener.ReadMessage().ToString();tlistener.ReceiveFile(filepath);if (tlistener.CalcFileHash(filepath) = t listener.ReadMessage() tlistener.SendMessage("ok");elsetlistener.SendMessage("wrong");#endregionif (firstMessage.ToLower() ="DBBak"elseLower()tlistener.SendMessage(#region 數據庫備份"dbbakok");stringfilename = tlistener.ReadMessage();stringfilepath = Path.Combine(System.Environment.CurrentDirectory,"DBBak" ) + ""+ filename;/接收文件tlistener.ReceiveFile(filepath);/驗證
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 教學工作參考總結高三語文教師期末個人參考總結
- 篷布遮陽篷在商業建筑的裝飾效果考核試卷
- 五年級下冊各單元好詞好句盤點
- 5-16一般同步時序電路的設計1-原始狀態轉移表的建立
- 北京市西城區北京師范大學附屬實驗中22024?2025學年學高一下學期階段測試一(3月) 數學試題(含解析)
- 晉城職業技術學院《誤差理論與測量平差基礎》2023-2024學年第一學期期末試卷
- 天津鐵道職業技術學院《風景園林專業導論課》2023-2024學年第二學期期末試卷
- 吉林省長春市汽開區達標名校2025屆重點高中聯盟領軍考試4月初三化學試題(文)試題含解析
- 天津大學《大學生創新創業與就業指導》2023-2024學年第一學期期末試卷
- 吉林醫藥學院《現代公司理論與實務》2023-2024學年第二學期期末試卷
- 小紅書食用農產品承諾書示例
- 水果店投資項目可行性分析報告
- CQI-23模塑系統評估審核表-中英文
- 《顱內壓增高的臨床表現》教學課件
- DB34T 4912-2024二手新能源汽車鑒定評估規范
- 會計記賬服務合同
- 四下第五單元課件
- 【教案】Unit+4+My+Favourite+Subject大單元整體教學設計人教版英語七年級上冊
- 出租車駕駛員解約合同范本
- 1《氓》公開課一等獎創新教學設計統編版高中語文選擇性必修上冊
- 江蘇省蘇州市2023-2024學年高一下學期期末考試化學試題(解析版)
評論
0/150
提交評論