




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、【背景】 最近做了一个双机备份,就是服务器上有个文件夹,会接收客户端传来的文件,而我们要做的就是同步这台服务器和另一台备用服务器上的文件. 为了实现这个功能我们使用的tcp点对点传输.【开发环境】 VS2005【实现原理】 要实现同步要解决两个问题,一个是获取本地服务器上上传上来的文件,二是实现两台机器间的文件传输. &
2、#160;第一个问题我们用的FileSystemWatcher这个可以监视指定文件夹下的文件变动,然后我们把变动的文件信息记录到数据库,在指定的时间间隔后同步两台机器的文件. 第二个问题我们用的tcp文件传输,我们按照一定的原则通过传输消息来告知备份服务器的要传输的文件名称和大小,然后传输文件.【代码】 1:FileSystemWatcher监视文件变动的就不介绍了,很简单的winform控件应用. 2:为了完成文件传输,
3、我做了一个TcpHelper类库,其中包括TcpCommon,TcpClientHelper,TcpListenerHelper三个类,TcpCommon主要实现了文件传输时用的一些公共的方法比如发送接收文件,发送接收消息,和文件hash的计算TcpCommonCodeusing System;using System.Collections.Generic;using System.Text;using System.Security.Cryptography;using System.IO;using System.Net.Soc
4、kets;namespace Xpwy.Backup.PTcpHelper internal class TcpCommon private static readonly int _blockLength = 500 * 1024;
5、0; / <summary> / 计算文件的hash值 / </summary> internal string CalcFileHash(string FilePath)
6、160; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte hash; &
7、#160; using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096)
8、; hash = md5.ComputeHash(fs); return BitConverter.ToString(hash);
9、 / <summary> / 发送文件 / </summary> / <param
10、name="filePath"></param> / <param name="stream"></param> / <returns></returns> internal
11、0;bool SendFile(string filePath, NetworkStream stream) FileStream fs = File.Open(filePath, FileMode.Open);
12、; int readLength = 0; byte data = new byte_blockLength; /发送大小
13、60; byte length = new byte8; BitConverter.GetBytes(new FileInfo(filePath).Length).CopyTo(length, 0);
14、0; stream.Write(length, 0, 8); /发送文件 while (readLength = fs.Read(data, 0, _blockLength) > 0) &
15、#160; stream.Write(data, 0, readLength);
16、; fs.Close(); return true; / <summary>
17、60; / 接收文件 / </summary> / <param name="filePath"></param> / <param name="stream&qu
18、ot;></param> / <returns></returns> internal bool ReceiveFile(string filePath, NetworkStream stream)
19、160; try long count = GetSize(stream);
20、60; if (count = 0)
21、0; return false; long index = 0;
22、0; byte clientData = new byte_blockLength; if (File.Exists(filePath)
23、; File.Delete(filePath); &
24、#160; string path=new FileInfo(filePath).Directory.FullName; if (!Directory.Exists(path) &
25、#160; Directory.CreateDirectory(path);
26、; FileStream fs = File.Open(filePath, FileMode.OpenOrCreate); try &
27、#160; &
28、#160; /计算当前要读取的块的大小 int currentBlockLength = 0;
29、 if (_blockLength < count - index)
30、; currentBlockLength = _blockLength;
31、60; else currentBloc
32、kLength =(int)( count - index); int
33、receivedBytesLen = stream.Read(clientData, 0, currentBlockLength); index += receivedBytesLen;
34、0; fs.Write(clientData, 0, receivedBytesLen); while (receivedBytesLen > 0 &&
35、;index < count) clientDa
36、ta = new byte_blockLength; receivedBytesLen = 0;
37、 if (_blockLength < count - index)
38、; currentBlockLength = _blockLength;
39、60; else
40、; currentBlockLength = (int)(count - index);
41、60; receivedBytesLen = stream.Read(clientData, 0, cur
42、rentBlockLength); index += receivedBytesLen; &
43、#160; fs.Write(clientData, 0, receivedBytesLen);
44、60; catch (Exception ex)
45、60; return false; finally
46、160; fs.Close();
47、60; catch (Exception ex)
48、60; return false; return true;
49、0; / <summary> / 发送消息 / </summary> / <param name="message"></param>
50、0; / <param name="stream"></param> / <returns></returns> internal bool SendMessage(string message, NetworkStream st
51、ream) byte data = Encoding.UTF8.GetBytes(message); byte resultData = new by
52、te8 + data.Length; BitConverter.GetBytes(data.Length).CopyTo(resultData, 0); data.CopyTo(resultData, 8);
53、0; stream.Write(resultData, 0, resultData.Length); return true; / <summary&g
54、t; / 读取消息 / </summary> / <param name="stream"></param> / &l
55、t;returns></returns> internal string ReadMessage(NetworkStream stream) string result = "&q
56、uot; int messageLength = 0; byte resultbyte = new byte500 * 1024;
57、 /读取数据大小 int index = 0; int count = GetSize(stream);
58、; byte data = new bytecount; while (index < count && (messageLength = stream.Read(data, 0, count - index) != 0)
59、; data.CopyTo(resultbyte, index); index
60、 += messageLength; result = Encoding.UTF8.GetString(resultbyte, 0, index);
61、; return result; / <summary> / 获取要读取的数据的大小 / </summary> &
62、#160; / <param name="stream"></param> / <returns></returns> private int GetSize(NetworkStream stream)
63、 int count = 0; byte countBytes = new byte8; &
64、#160; try if (stream.Read(countBytes, 0, 8) = 8) &
65、#160; count = BitConverter.ToInt32(countBytes, 0);
66、160; else
67、0; return 0;
68、160; catch (Exception ex) return count;
69、160; TcpClientHelperCodeusing System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;namespace Xpwy.Backup.PTcpHelper public class TcpClientHelper:IDisposable
70、60; TcpClient client; NetworkStream netstream; string _serverip = ""
71、; int _port = 8080; TcpCommon tcpCommon = new TcpCommon(); #region TcpClientHelper constructor public Tc
72、pClientHelper(string strServerIP, int serverPort) _serverip = strServerIP; _port
73、;= serverPort; #endregion public void Start()
74、160; client = new TcpClient(_serverip, _port); netstream = client.GetStream(); public
75、160;void Stop() if (netstream != null)
76、60; netstream.Close(); if (client != null)
77、; client.Close(); #region&
78、#160;TcpCommon所有方法 public string CalcFileHash(string FilePath) return tcpCommon.CalcFileHash(FilePath);
79、; public bool SendFile(string filePath) return tcpCommon.SendFile(filePath,
80、60;netstream); public bool ReceiveFile(string filePath) return tcp
81、Common.ReceiveFile(filePath, netstream); public bool SendMessage(string message)
82、60; return tcpCommon.SendMessage(message, netstream); public string ReadMessage()
83、60; return tcpCommon.ReadMessage(netstream); #endregion #region IDisposable 成员
84、 public void Dispose() if (netstream != null)
85、0; netstream.Close(); if (client != null)
86、 client.Close();
87、60; #endregion TcpListenerHelperCodeusing System;using System.Collections.Generic;using System.Text;using System.Net.Sockets;using System.Net;using System.Threading;namespace Xpwy.Backup.PTcpHelper public clas
88、s TcpListenerHelper private string _strServerIP = "" private int _serverPort = 0;
89、0;TcpListener server; TcpClient client; NetworkStream netstream; IAsyncResult asyncResult; T
90、cpCommon tcpCommon = new TcpCommon(); ManualResetEvent listenConnected = new ManualResetEvent(false); bool _active = false;
91、0; public TcpListenerHelper(string strServerIP, int serverPort) _strServerIP = strServerIP; &
92、#160; _serverPort = serverPort; server = new TcpListener(IPAddress.Parse(strServerIP), serverPort); serve
93、r.Server.ReceiveTimeout = 6000; server.Server.SendTimeout = 6000; / <summary>
94、160; / 启动 / </summary> public void Start() t
95、ry _active = true; server.St
96、art(); catch (Exception ex)
97、 throw ex; / <summary>
98、/ 停止 / </summary> public void Stop() try
99、60; _active = false; if (client != nu
100、ll) client.Close();
101、 if (netstream != null)
102、; netstream.Close(); server.Stop
103、(); catch (Exception ex)
104、60; throw ex; &
105、#160; public void Listen() listenConnected.Reset(); asyncResult = server.
106、BeginAcceptTcpClient(new AsyncCallback(AsyncCall), server); public void AsyncCall(IAsyncResult ar)
107、0; try TcpListener tlistener = (TcpListener)ar.AsyncState; &
108、#160; if (_active)
109、160;client = tlistener.EndAcceptTcpClient(ar); netstream = client.GetStream();
110、; else &
111、#160; client = null; netstream = null;
112、0; listenConnected.Set(); catch (Exception ex)
113、 throw ex;
114、0; public bool WaitForConnect() listenConnected.WaitOne(); if
115、0;(client != null && netstream != null) return true;
116、160; else return false;
117、0; #region TcpCommon所有方法 / <sum
118、mary> / 计算文件的hash值 / </summary> public string CalcFileHash(string FilePath)
119、160; return tcpCommon.CalcFileHash(FilePath); / <summary> / 发送文件
120、160; / </summary> / <param name="filePath"></param> / <returns></returns>
121、160; public bool SendFile(string filePath) return tcpCommon.SendFile(filePath, netstream); &
122、#160; / <summary> / 接收文件 / </summary> / <param name="filePath"></par
123、am> / <returns></returns> public bool ReceiveFile(string filePath)
124、60; return tcpCommon.ReceiveFile(filePath, netstream); / <summary> / 发送消息
125、/ </summary> / <param name="message"></param> / <returns></returns> public bool SendMessa
126、ge(string message) return tcpCommon.SendMessage(message, netstream); /&
127、#160;<summary> / 接收消息 / </summary> / <returns></returns> public stri
128、ng ReadMessage() return tcpCommon.ReadMessage(netstream); #endregion
129、160; #region IDisposable 成员 public void Dispose() Stop();
130、0; #endregion 3:调用的代码server端: Codepublic void DoWork(object state)
131、 TcpListenerHelper tlistener = (TcpListenerHelper)state; tlistener.Listen();/监听 while (tlistener.
132、WaitForConnect()/等待知道监听到了连接 try
133、 string firstMessage = "" while (!stri
134、ng.IsNullOrEmpty(firstMessage = tlistener.ReadMessage() &
135、#160; if (firstMessage.ToLower() = "filebak".ToLower()
136、 tlistener.SendMessage("filebakok");
137、60; #region 文件备份 string filepath = Path.Combine(Environment.CurrentDirectory, "F
138、ileBak" + tlistener.ReadMessage().ToString(); tlistener.ReceiveFile(filepath);
139、0; if (tlistener.CalcFileHash(filepath) = tlistener.ReadMessage()
140、; tlistener.SendMessage("ok"
141、;);
142、60; else
143、; tlistener.SendMessage("wrong");
144、 #endregion
145、160; else if (firstMessage.ToLower() = "DBBak".ToLower()
146、; #region 数据库备份
147、; tlistener.SendMessage("dbbakok");
148、0; string filename = tlistener.ReadMessage(); string&
149、#160;filepath = Path.Combine(System.Environment.CurrentDirectory, "DBBak") +""+ filename;
150、0;/接收文件 tlistener.ReceiveFile(filepath);
151、60; /验证hash值 string hash = tlistener.ReadMessag
152、e(); if (hash = tlistener.CalcFileHash(filepath)
153、0; tlistener.SendMessage("ok"); else
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 民爆安全培训课件
- 船舶机舱考试题库及答案
- 测量考试题库及答案解析
- 特色新质生产力发展模式与案例
- 发展新质生产力的主要做法
- 民族舞课程课件
- 全球新质生产力的发展现状
- 2025年微生物学临床微生物培养鉴定操作评估试卷答案及解析
- 三中全会新质生产力解读
- 2025年胸心外科胸部手术术中护理操作考核答案及解析
- 《劳动工具的改进设计》六年级综合实践课件
- 村级换届业务培训
- 《三角函数的诱导公式(第1课时)》导学案2
- 全国赛课一等奖2024版新教材统编版七年级历史上册《中华文明的起源》课件
- GB/T 22838.5-2024卷烟和滤棒物理性能的测定第5部分:卷烟吸阻和滤棒压降
- 江苏省镇江市2024-2025学年高三上学期期初考试数学试卷(解析版)
- 全国职业院校技能大赛高职组(供应链管理赛项)备赛试题库(含答案)
- JT叔叔医道课1-50集完整稿
- 部编版五年级道德与法治上册第3课《主动拒绝烟酒与毒品》精美课件(第3课时)
- JB-T 8881-2020 滚动轴承 渗碳轴承钢零件 热处理技术条件
- 2024年四川省水电投资经营集团普格电力有限公司招聘笔试参考题库含答案解析
评论
0/150
提交评论