C# TCP发送消息和传输文件.doc_第1页
C# TCP发送消息和传输文件.doc_第2页
C# TCP发送消息和传输文件.doc_第3页
C# TCP发送消息和传输文件.doc_第4页
C# TCP发送消息和传输文件.doc_第5页
已阅读5页,还剩2页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

C# TCP发送消息和传输文件本文由zhangzh2003贡献 doc文档可能在WAP端浏览体验不佳。建议您优先选择TXT,或下载源文件到本机查看。 【背景】 最近做了一个双机备份,就是服务器上有个文件夹,会接收客户端传来的文件,而我们要 做的就是同步这台服务器和另一台备用服务器上的文件. 为了实现这个功能我们使用的 tcp 点对点传输. 【开发环境】 VS2005 【实现原理】 要实现同步要解决两个问题,一个是获取本地服务器上上传上来的文件,二是实现两台机 器间的文件传输. 第一个问题我们用的 FileSystemWatcher 这个可以监视指定文件夹下的文件变动,然 后我们把变动的文件信息记录到数据库,在指定的时间间隔后同步两台机器的文件. 第二个问题我们用的 tcp 文件传输,我们按照一定的原则通过传输消息来告知备份服务 器的要传输的文件名称和大小,然后传输文件. 【代码】 1:FileSystemWatcher 监视文件变动的就不介绍了,很简单的 winform 控件应用. 2:为了完成文件传输,我做了一个 TcpHelper 类库,其中包括 TcpCommon,TcpClientHelper,TcpListenerHelper 三个类,TcpCommon 主要实现了 文件传输时用的一些公共的方法比如发送接收文件,发送接收消息,和文件 hash 的计算 TcpCommon using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; using System.Net.Sockets; namespace Xpwy.Backup.PTcpHelper internal class TcpCommon private static readonly int _blockLength = 500 * 1024; / / 计算文件的 hash 值 / internal string CalcFileHash(string FilePath) MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvid er(); byte hash; using (FileStream fs = new FileStream(FilePath, FileMode. Open, FileAccess.Read, FileShare.Read, 4096) hash = md5.ComputeHash(fs); return BitConverter.ToString(hash); / / 发送文件 / / / / internal bool SendFile(string filePath, NetworkStream stream) FileStream fs = File.Open(filePath, FileMode.Open); int readLength = 0; byte data = new byte_blockLength; /发送大小 byte length = new byte8; BitConverter.GetBytes(new FileInfo(filePath).Length).Copy To(length, 0); stream.Write(length, 0, 8); /发送文件 while (readLength = fs.Read(data, 0, _blockLength) 0) stream.Write(data, 0, readLength); fs.Close(); return true; / / 接收文件 / / / / internal bool ReceiveFile(string filePath, NetworkStream stre am) try long 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.Exists(path) Directory.CreateDirectory(path); FileStream fs = File.Open(filePath, FileMode.OpenOrCr eate); try /计算当前要读取的块的大小 int currentBlockLength = 0; if (_blockLength 0 & index count) clientData = new byte_blockLength; receivedBytesLen = 0; if (_blockLength count - index) currentBlockLength = _blockLength; else currentBlockLength = (int)(count - index); receivedBytesLen = stream.Read(clientDat a, 0, currentBlockLength); index += receivedBytesLen; fs.Write(clientData, 0, receivedBytesLen); catch (Exception ex) return false; finally fs.Close(); catch (Exception ex) return false; return true; / / 发送消息 / / / / internal bool SendMessage(string message, NetworkStream strea m) byte data = Encoding.UTF8.GetBytes(message); byte resultData = new byte8 + data.Length; BitConverter.GetBytes(data.Length).CopyTo(resultData, 0); data.CopyTo(resultData, 8); stream.Write(resultData, 0, resultData.Length); return true; / / 读取消息 / / / internal string ReadMessage(NetworkStream stream) string result = ; int messageLength = 0; byte resultbyte = new byte500 * 1024; /读取数据大小 int index = 0; int count = GetSize(stream); byte data = new bytecount; while (index count & (messageLength = stream.Read(dat a, 0, count - index) != 0) data.CopyTo(resultbyte, index); index += messageLength; result = Encoding.UTF8.GetString(resultbyte, 0, index); return result; / / 获取要读取的数据的大小 / / / private int GetSize(NetworkStream stream) int count = 0; byte countBytes = new byte8; try if (stream.Read(countBytes, 0, 8) = 8) count = BitConverter.ToInt32(countBytes, 0); else return 0; catch (Exception ex) return count; TcpClientHelper using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace Xpwy.Backup.PTcpHelper public class TcpClientHelper:IDisposable 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; #endregion public void 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 SendFile(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.ReadMessage(netstream); #endregion #region IDisposable 成员 public void Dispose() if (netstream != null) netstream.Close(); if (client != null) client.Close(); #endregion TcpListenerHelper using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; namespace Xpwy.Backup.PTcpHelper public class TcpListenerHelper private string _strServerIP = ; private int _serverPort = 0; TcpListener server; TcpClient client; NetworkStream netstream; IAsyncResult asyncResult; TcpCommon tcpCommon = new TcpCommon(); ManualResetEvent listenConnected = new ManualResetEvent(fals e); bool _active = false; public TcpListenerHelper(string strServerIP, int serverPort) _strServerIP = strServerIP; _serverPort = serverPort; server = new TcpListener(IPAddress.Parse(strServerIP), se rverPort); server.Server.ReceiveTimeout = 6000; server.Server.SendTimeout = 6000; / / 启动 / public void Start() try _active = true; server.Start(); catch (Exception ex) throw ex; / / 停止 / 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 Listen() listenConnected.Reset(); asyncResult = server.BeginAcceptTcpClient(new AsyncCallba ck(AsyncCall), server); public void AsyncCall(IAsyncResult ar) try TcpListener tlistener = (TcpListener)ar.AsyncState; if (_active) client = tlistener.EndAcceptTcpClient(ar); netstream = client.GetStream(); else client = null; netstream = null; listenConnected.Set(); catch (Exception ex) throw ex; public bool WaitForConnect() listenConnected.WaitOne(); if (client != null & netstream != null) return true; else return false; #region TcpCommon 所有方法 / / 计算文件的 hash 值 / public string CalcFileHash(string FilePath) return tcpCommon.CalcFileHash(FilePath); / / 发送文件 / / / public bool SendFile(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.ReadMessage(netstream); #endregion #region IDisposable 成员 public void Dispose() Stop(); #endregion 3:调用的代码 server 端: public void DoWork(object state) TcpListenerHelper tlistener = (TcpListenerHelper)state; tlistener.Listen();/监听 while (tlistener.WaitForConnect()/等待知道监听到了连接 try string firstMessage = ; while (!string.IsNullOrEmpty(firstMessage = tlis tener.ReadMessage() if (firstMessage.ToLower() = filebak.ToLow er() tlistener.SendMessage(filebakok); #region 文件备份 string filepath = Path.Combine(Environmen t.CurrentDirectory, FileBak + tlistener.ReadMessage().ToString(); tlistener.ReceiveFile(filepath); if (tlistener.CalcFileHash(filepath) = t listener.ReadMessage() tlistener.SendMessage(ok); else tlistener.SendMessage(wrong); #endregion else if (firstMessage.ToLower() = DBBak.To Lower() #region 数据库备份 tlistener.SendMessage(dbbakok); string filename = tlistener.ReadMessage(); string filepath = Path.Combine(System.Env ironment.CurrentDirectory, DBBak) + filename; /接收文件 tlistener.ReceiveFile

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论