




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、三個類,TcpCommon 主要實現(xiàn)了,發(fā)送接收消息,和文件hash的計算_blockLength =500 *1024string FilePath)new MD5CryptoServiceProvid【背景】最近做了一個雙機備份,就是服務器上有個文件夾,會接收客戶端傳來的文件,而我們要 做的就是同步這臺服務器和另一臺備用服務器上的文件為了實現(xiàn)這個功能我們使用的 tcp點對點傳輸.【開發(fā)環(huán)境】VS2005【實現(xiàn)原理】要實現(xiàn)同步要解決兩個問題,一個是獲取本地服務器上上傳上來的文件,二是實現(xiàn)兩臺機器間的文件傳輸.第一個問題我們用的 FileSystemWatcher這個可以監(jiān)視指定文件夾下的文件
2、變動,然后我們把變動的文件信息記錄到數(shù)據(jù)庫,在指定的時間間隔后同步兩臺機器的文件.第二個問題我們用的tcp文件傳輸,我們按照一定的原則通過傳輸消息來告知備份服務器的要傳輸?shù)奈募Q和大小,然后傳輸文件.【代碼】1:FileSystemWatcher監(jiān)視文件變動的就不介紹了,很簡單的winform 控件應用.2:為了完成文件傳輸,我做了一個TcpHelper類庫,其中包括TcpCommon,TcpClientHelper,TcpListenerHelper文件傳輸時用的一些公共的方法比如發(fā)送接收文件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 / 發(fā)送文件 / /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;/發(fā)送大小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)/發(fā)送文件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 /發(fā)送消息/ /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 ;/讀取數(shù)據(jù)大小 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>/獲取要讀取的數(shù)據(jù)的大小/ </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/發(fā)送文件/ /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/發(fā)送消息/ /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:調(diào)用的代碼server 端:EEpublic void DoWork( object state)TcpListenerHelper tlistener = (TcpListenerHelper)state;tlistener.Listen();/ 監(jiān)聽/等待知
28、道監(jiān)聽到了連接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 數(shù)據(jù)庫備份"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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2010-2024歷年浙江省樂清市第二中學高一第二次月考政治試卷(帶解析)
- 2025山東省水工環(huán)地質(zhì)工程有限公司招聘(15名)筆試參考題庫附帶答案詳解版
- 備戰(zhàn)高一高二高三高考歷史臨考題號押題-押江蘇卷第20題近代歐美國家的發(fā)展(解析版)
- 2010-2024歷年廣東東莞南開實驗學校九年級上期中英語試卷(帶解析)
- 2024年百色市平果市科技館聘用人員招聘筆試真題
- 浙江省機關事務管理局事業(yè)單位真題2024
- 2024年納米抗菌管資金籌措計劃書代可行性研究報告
- 福建平潭綜合實驗區(qū)實業(yè)發(fā)展集團有限公司招聘考試真題2024
- 中組部干部選拔管理辦法
- 集團登記管理暫行辦法
- 摩托車協(xié)議過戶協(xié)議書
- 2025年食品檢驗員考試試卷及答案
- 四川省德陽市2025年七年級下學期語文期末試卷及答案
- 黎族文化課件
- 中華人民共和國民營經(jīng)濟促進法
- 色彩的魅力:藝術、科學與設計的交融
- 2025廣州市荔灣區(qū)輔警考試試卷真題
- 一季度安委會匯報材料
- 貴州省遵義市2024年八年級《數(shù)學》上學期期末試題與參考答案
- 產(chǎn)品質(zhì)量問題追溯制度
- TACE圍手術期的護理
評論
0/150
提交評論