工作需要,经常会在工作的台式机和笔记本之间传文件或者需要拷贝文本,两个机器都位于局域网内,传文件或者文本的方式有很多种,之前是通过共享文件夹来进行文件的拷贝,或者通过SVN进行同步。文本传递比较简单,可以通过两台机器上装QQ登两个号码,或者在共享目录下建一个TXT,或者发电子邮件等等。

不过上面这些方法总觉得不直接,所以想基于P2P做一个小的局域网文件和文字传输小工具。

WinForm的工程,界面方面的代码就不贴了,大家自己根据喜好设计就好了,主要把TCP数据传输的代码和逻辑贴出来:

1. 文件和文本传输的通用方法:

private string ReceiveControl(Socket socket)
{
int bufSize = 1024;
byte[] buf = new byte[bufSize];
int len = socket.Receive(buf);
return len > 0 ? Encoding.UTF8.GetString(buf, 0, len) : String.Empty;
}
private void SendControl(Socket socket, string controlMsg)
{
byte[] msgBytes = Encoding.UTF8.GetBytes(controlMsg);
socket.Send(msgBytes);
}
private string ReceiveContent(Socket socket, int contentLen)
{
int receivedLen = 0;
int bufSize = 1024;
byte[] buf = new byte[bufSize];
StringBuilder sb = new StringBuilder();
while (receivedLen < contentLen)
{
int len = socket.Receive(buf);
if (len > 0)
{
sb.Append(Encoding.UTF8.GetString(buf, 0, len));
receivedLen += len;
}
}
return sb.ToString();
}
private void SendContent(Socket socket, string content)
{
byte[] contentBytes = Encoding.UTF8.GetBytes(content);
SendControl(socket, contentBytes.Length.ToString());
ReceiveControl(socket);
socket.Send(contentBytes);
}
private void ReceiveFile(Socket socket, string fileName, int fileLen)
{
string filePath = Path.Combine(GetCurrentUserDesktopPath(), RenameConflictFileName(fileName));
using (Stream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
int bufLen = 1024;
int receivedLen = 0;
byte[] buf = new byte[bufLen];
int len = 0;
while (receivedLen < fileLen)
{
len = socket.Receive(buf);
fs.Write(buf, 0, len);
receivedLen += len;
}
}
}
private void SendFile(Socket socket, string filePath)
{
using (Stream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
SendControl(socket, GetFileNameFromPath(filePath));
ReceiveControl(socket);
SendControl(socket, fs.Length.ToString());
ReceiveControl(socket);
int bufLen = 1024;
byte[] buf = new byte[bufLen];
long readLen = 0;
long fileLen = fs.Length;
int len = 0;
while (readLen < fileLen)
{
len = fs.Read(buf, 0, bufLen);
readLen += len;
int sentLen = 0;
int realSent = 0;
int left = 0;
while (sentLen < len)
{
left = len - realSent;
realSent = socket.Send(buf, sentLen, left, SocketFlags.None);
sentLen += realSent;
}
}
}
}

2.连接,发送文字/文件,重命名文件等方法:

private void SendText()
{if (connected){if (!String.IsNullOrEmpty(this.TextToSend.Text)){string txt = this.TextToSend.Text;SendControl(clientSocket, "Text");ReceiveControl(clientSocket);SendContent(clientSocket, txt);ReceiveControl(clientSocket);}}
}private void Connect()
{try{if (!connected){passive = false;IPAddress serverIPAddress = IPAddress.Parse(this.ServerIPAddress.Text);clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);clientSocket.Connect(serverIPAddress, 60000);string msg = ReceiveControl(clientSocket);if (msg.Equals("Connected")){this.ConnectBtn.Text = "Disconnect";connected = true;}}else{passive = true;SendControl(clientSocket, "Disconnect");clientSocket.Close();this.ConnectBtn.Text = "Connect";connected = false;}}catch (Exception err){MessageBox.Show(string.Format("Failed to connect to server, error: {0}", err.ToString()));}
}private void ServerThread()
{IPAddress local = IPAddress.Parse("0.0.0.0");Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);server.Bind(new IPEndPoint(local, 60000));server.Listen(1);while (true){Socket receivedClientSocket = server.Accept();IPEndPoint clientEndPoint = (IPEndPoint)receivedClientSocket.RemoteEndPoint;SendControl(receivedClientSocket, "Connected");if (passive){clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);clientSocket.Connect(clientEndPoint.Address, 60000);string msg = ReceiveControl(clientSocket);if (msg.Equals("Connected")){connected = true;this.ConnectBtn.Text = "Disconnect";this.ServerIPAddress.Text = clientEndPoint.Address.ToString();}}while (connected){string msg = ReceiveControl(receivedClientSocket);switch (msg){case "Disconnect":receivedClientSocket.Close();clientSocket.Close();this.ConnectBtn.Text = "Connect";passive = true;connected = false;break;case "Text":SendControl(receivedClientSocket, "Received");int length = Convert.ToInt32(ReceiveControl(receivedClientSocket));SendControl(receivedClientSocket, "Received");string content = ReceiveContent(receivedClientSocket, length);SendControl(receivedClientSocket, "Received");this.TextToSend.Text = content;break;case "File":SendControl(receivedClientSocket, "Received");string fileName = ReceiveControl(receivedClientSocket);SendControl(receivedClientSocket, "Received");int fileLen = Convert.ToInt32(ReceiveControl(receivedClientSocket));SendControl(receivedClientSocket, "Received");ReceiveFile(receivedClientSocket, fileName, fileLen);SendControl(receivedClientSocket, "Received");MessageBox.Show("File Received");break;}}}
}private string GetFileNameFromPath(string path)
{int index = path.LastIndexOf('\\');return path.Substring(index + 1);
}private string RenameConflictFileName(string originalName)
{string desktopPath = GetCurrentUserDesktopPath();int extensionIndex = originalName.LastIndexOf(".");string fileName = originalName.Substring(0, extensionIndex);string extensionName = originalName.Substring(extensionIndex + 1);int renameIndex = 1;string newNameSuffix = String.Format("({0})", renameIndex);string finalName = originalName;string filePath = Path.Combine(desktopPath, finalName);if (File.Exists(filePath)){finalName = String.Format("{0} {1}.{2}", fileName, newNameSuffix, extensionName);filePath = Path.Combine(desktopPath, finalName);}while (File.Exists(filePath)){renameIndex += 1;string oldNameSuffix = newNameSuffix;newNameSuffix = String.Format("({0})", renameIndex);finalName = finalName.Replace(oldNameSuffix, newNameSuffix);filePath = Path.Combine(desktopPath, finalName);}return finalName;
}private string GetCurrentUserDesktopPath()
{return Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
}

运行截图:

完整代码可以到下面的地址下载:

http://download.csdn.net/detail/qwertyupoiuytr/9895436



C#实现一个局域网文件传输工具相关推荐

  1. 小试跨平台局域网文件传输工具NitroShare,几点感想

    随着电脑系统国产化的推进,单位用的OA系统已转移到国产电脑上了,但是国产电脑上的操作系统基于Linux,软件商店里可选的应用软件还不够多,功能也还有待提高.为了提高处理效率,经常需要把文件从国产电脑传 ...

  2. python 编写一个局域网文件传输的程序

    可以使用 Python 的 socket 模块来编写一个局域网文件传输程序. 首先,你需要在服务端程序中创建一个 socket 对象,并绑定到特定的 IP 地址和端口上.然后,服务端可以通过调用 so ...

  3. ubuntu、win跨平台局域网文件传输工具

    DuktoR6 官网:https://www.msec.it/blog/dukto/  win10不可使用 NitroShare官网:https://nitroshare.net/     win10 ...

  4. LocalSend - 文件传输工具

    前言 LocalSend是一种快速高效的局域网文件传输工具,它无广告,速度快,只需文件权限,无需蓝牙权限.值得一提的是,手机开热点给电脑,也可以在手机和电脑直接传输文件:以太网和WiFi只要属于同一局 ...

  5. linux串口文件传输工具

    起因: 有块开发板需要调试app程序,但没有网口,编译的app没法传进去.如果采用通过把app打包到文件系统中,然后把文件系统重新刷到板子上的方法,非常的不方便,调试也很麻烦. 开发板环境: 架构:a ...

  6. 局域网传文件_局域网文件分享工具 Feem,这些高级功能值得付费!

    局域网文件分享,面对面传文件,肿么破? 坐拥苹果生态圈的用户不用愁,使用 AirDrop 快如闪电,但工作.学习,难免会接触到其他的平台,这时候想要获得一致的使用体验,不太容易. 部分知名的分享工具光 ...

  7. vb.net 局域网传文件_局域网文件分享工具 Feem,这些高级功能值得付费!

    局域网文件分享,面对面传文件,肿么破? 坐拥苹果生态圈的用户不用愁,使用 AirDrop 快如闪电,但工作.学习,难免会接触到其他的平台,这时候想要获得一致的使用体验,不太容易. 部分知名的分享工具光 ...

  8. 局域网限制网速软件_大文件传输工具,比微信、QQ文件传输还好用的传输软件,关键还不限速!...

    白剽一个专注分享各种软件资源的平台 软件名称:文件传输助手 如果你觉得本篇文章对你有帮助,麻烦你给我本篇文章的文末点一个[在看]就是对我最大的帮助,白嫖党和伸手党真的不好,正所谓赠人玫瑰手留余香,我帮 ...

  9. vivo手机互传的文件怎么找到_基于 P2P 的在线文件传输工具,电脑与手机互传文件...

    小鹿快传是一款点对点(P2P)的在线文件传输工具,无需登录,即可在电脑.手机间互传文件,简单方便快捷. 小鹿快传是一款在线工具,只需要使用浏览器打开即可传输.无论电脑与电脑之间,手机与手机之间,还是电 ...

  10. feem v4 Android,Feem app下载-Feem安卓版(文件传输工具)下载 v4.3.2_5577安卓网

    Feem app推荐给需要一款文件传输软件的用户,app支持多个平台之间传输,而且传输速度超快,非常适合传输较大的软件,即使是这样也完全不卡顿,只要将设备放置同一个无线网络下就能进行传输. [软件介绍 ...

最新文章

  1. VS中编译64位程序以及遇到的问题(E0000235)
  2. 解决VS2015 VBCSCompiler.exe 占用CPU100%的问题
  3. java基础格式_Java基础之代码的基本格式
  4. java swt 不显示图片_Java SWT按钮图像未刷新
  5. 工作158:vue里面为什么要加key
  6. 八、pink老师的学习笔记—— CSS用户界面样式(鼠标样式、轮廓线、防止拖拽文本域)
  7. [bzoj4994][Usaco2017 Feb]Why Did the Cow Cross the Road III_树状数组
  8. 建设“一流本科专业”?急啥,先看看哈佛数学系从三流到一流的150年
  9. 求两条轨迹间的hausdorff距离_题型 | 圆上有n个点到直线距离为d?
  10. 转载 侃一侃编译原理的“文法” 作者 :博客网 my笔触
  11. 地图之美(地图制图)
  12. IDEA报Invalid bound statement (not found)错误解决办法
  13. 魅蓝手机ROOT权限获取
  14. 关机一直显示正在关闭服务器,电脑关机后,显示正在关机,但等半天也关不了 怎么办...
  15. 计算机专业课838,838计算机科学专业基础综合.docx
  16. 微信摇一摇插件ios_iOS仿微信摇一摇功能
  17. AS608指纹模块高级功能实现(一):底层数据传输——指纹特征库上传给上位机
  18. jenkins忘记管理员密码修改
  19. 软件测试公司都会查学历吗,高新技术企业申请会查员工学历吗?申请高新技术企业注意事项解读...
  20. termux使用教程python-利用Termux超级终端在手机上运行Python开发环境

热门文章

  1. webpower中小企业邮件营销指南
  2. python语音识别_Python语音识别终极指南
  3. 今日头条mysql面试题_【今日头条】测试工程师面试题
  4. 【信号与系统】DTFT离散时间傅里叶变换
  5. 视频直播系统源码,比较图片
  6. 应用EtherNet IP转Modbus网关连接施耐德PLC和AB PLC
  7. Lattice Diamond 学习总结---“疑难杂症”杂篇
  8. 简易网站流量统计工具
  9. Hive常用正则表达式
  10. google四件套之Dagger2。从入门到爱不释手,之:Dagger2进阶知识及在Android中使用