C#_TCP发送消息和传输文件最近做了一个双机备份,就是服务器上有个文件夹,会接收客户端传来的文件,而我们要做的就是同步这台服务器和另一台备用服务器上的文件. 为了实现这个功能我们使用的tcp点对点传输.【开发环境】 VS2005【实现原理】 要实现同步要解决两个问题,一个是获取本地服务器上上传上来的文件,二是实现两台机器间的文件传输. 第一个问题我们用的FileSystemWatcher这个可以监视指定文件夹下的文件变动,然后我们把变动的文件信息记录到数据库,在指定的时间间隔后同步两台机器的文件. 第二个问题我们用的tcp文件传输,我们按照一定的原则通过传输消息来告知备份服务器的要传输的文件名称和大小,然后传输文件.【代码】 1:FileSystemWatcher监视文件变动的就不介绍了,很简单的winform控件应用. 2:为了完成文件传输,我做了一个TcpHelper类库,mon,TcpClientHelper,TcpListenerHelper三个类,mon主要实现了文件传输时用的一些公共的方法比如发送接收文件,发送接收消息,monCodeusing System;using ;using ;using ;using ;using .Sockets;namespace { internal class mon { private static readonly int _blockLength = 500 * 1024; /// <summary> /// 计算文件的hash值 /// </summary> internal string CalcFileHash(string FilePath) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash; using (FileStream fs = new FileStream(FilePath, , , , 4096)) { hash = puteHash(fs); } return (hash); } /// <summary> /// 发送文件 /// </summary> /// <param name="filePath"></param> /// <param name="stream"></param> /// <returns></returns> internal bool SendFile(string filePath, NetworkStream stream) { FileStream fs = (filePath, ); int readLength = 0; byte[] data = new byte[_blockLength]; //发送大小 byte[] length = new byte[8]; (new FileInfo(filePath).Length).CopyTo(length, 0); (length, 0, 8); //发送文件 while ((readLength = (data, 0, _blockLength)) > 0) { (data, 0, readLength); } (); return true; } /
C# TCP发送消息和传输文件 来自淘豆网m.daumloan.com转载请标明出处.