C#实现TFTP客户端

1、文件结构
在这里插入图片描述
2、TftpConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace TftpTest
{public class TftpConfig{}/// <summary>/// 模式/// </summary>public enum Modes{NETASCII = 0,   //ASCIIOCTET = 1       //二进制}/// <summary>/// 操作码/// </summary>public enum OpCodes{RRQ = 1,    // 读请求WRQ = 2,    // 写请求DATA = 3,   // 数据ACK = 4,    // AcknowledgeERROR = 5,  // 错误OACK = 6    // Option Acknowledge}public enum TransferType{Get,Put}public struct TransferOptions{private TransferType _action;public TransferType Action{get { return _action; }set { _action = value; }}private string _localFilename;public string LocalFilename{get { return _localFilename; }set { _localFilename = value; }}private string _remoteFilename;public string RemoteFilename{get { return _remoteFilename; }set { _remoteFilename = value; }}private string _host;public string Host{get { return _host; }set { _host = value; }}}
}

3、ErrorPacket.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace TftpTest
{public class ErrorPacket{short _code;public short Code{get { return _code; }set { _code = value; }}string _message;public string Message{get { return _message; }set { _message = value; }}public ErrorPacket(short Code, string Message){Code = _code;Message = _message;}}
}

4、PacketBuilder.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace TftpTest
{public class PacketBuilder{public byte[] Request(OpCodes OpCode, string RemoteFileName,Modes Mode, int BlockSize, long TransferSize, int Timeout){// Request packet structure// -----------------------------------------------------------------------------// |OpCode|FileName|0|Mode|0|BlkSize|0|BSVal|0|TSize|0|TSVal|0|Timeout|0|TVal|0|// -----------------------------------------------------------------------------int len;string packetStr = "";string mode = Mode.ToString().ToLower();string blockSize = BlockSize.ToString();string nullChar = "\0";byte[] packet;// Create packet as a stringswitch (OpCode){case OpCodes.RRQ:packetStr = nullChar + (char)1;break;case OpCodes.WRQ:packetStr = nullChar + (char)2;break;}packetStr += RemoteFileName + nullChar + mode + nullChar + "blksize" +nullChar + BlockSize.ToString() + nullChar + "tsize" + nullChar +TransferSize.ToString() + nullChar + "timeout" + nullChar +Timeout.ToString() + nullChar;len = packetStr.Length;packet = new byte[len];// Encode packet as ASCII bytespacket = System.Text.Encoding.ASCII.GetBytes(packetStr);return packet;}public byte[] Ack(int Block1, int Block2){// ACK packet structure// ----------// |04|Block|// ----------byte[] packet = new byte[4];packet[0] = 0;packet[1] = (byte)OpCodes.ACK;packet[2] = (byte)Block1;packet[3] = (byte)Block2;return packet;}public byte[] Data(byte[] SendData, int Block1, int Block2){// DATA packet structure// ----------// |03|Block|// ----------byte[] packet = new byte[SendData.Length + 4];//packet[0] = 0;packet[1] = (byte)OpCodes.DATA;packet[2] = (byte)Block1;packet[3] = (byte)Block2;for (int h = 4; h < SendData.Length + 4; h++){packet[h] = SendData[h - 4];}return packet;}public int[] IncrementBock(byte[] ReceivedData, int[] Block){if (ReceivedData[3] == 255){if (ReceivedData[2] < 255){Block[0] = (int)ReceivedData[2] + 1; Block[1] = 0;}else{Block[0] = 0; Block[1] = 0;}}else{Block[1] = (int)ReceivedData[3] + 1;}return Block;}}
}

5、PacketReader.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace TftpTest
{public class PacketReader{public OpCodes ReadOpCode(byte[] ReceivedData){return (OpCodes)ReceivedData[1];}public int ReadTransferSize(byte[] ReceivedData){int h, tSize = 0;string searchStr, decPacket = Encoding.ASCII.GetString(ReceivedData);char[] splitChar = { '\0' };string[] splitPacket = decPacket.Split(splitChar);for (h = 0; h < splitPacket.Length - 1; h++){searchStr = splitPacket[h].ToLower();if (searchStr == "tsize"){tSize = int.Parse(splitPacket[h + 1]);}}return tSize;}public ErrorPacket ReadError(byte[] ReceivedData){string codeStr = ReceivedData[2].ToString() + ReceivedData[3].ToString();short code = short.Parse(codeStr);string message = "";for (int h = 4; h < ReceivedData.Length; h++){if (ReceivedData[h] == 0)break;message += (char)ReceivedData[h];}return new ErrorPacket(code, message);}public bool CompareBlocks(byte[] SentData, byte[] ReceivedData){if (ReceivedData[2] == SentData[2] &&ReceivedData[3] == SentData[3])return true;return false;}}
}

6、TftpClient.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;namespace TftpTest
{public class TftpClient{// 委托public delegate void ConnectedHandler();public delegate void TransferringHandler(long BytesTransferred, long BytesTotal);public delegate void TransferFailedHandler(short ErrorCode, string ErrorMessage);public delegate void TransferFinishedHandler();public delegate void DisconnectedHandler();// 事件public event ConnectedHandler Connected;public event TransferringHandler Transferring;public event TransferFailedHandler TransferFailed;public event TransferFinishedHandler TransferFinished;public event DisconnectedHandler Disconnected;private string _host;[Description("主机")]public string Host{get { return _host; }set { _host = value; }}private Modes _mode = Modes.OCTET;[Description("模式")]public Modes Mode{get { return _mode; }set { _mode = value; }}private int _blockSIze = 512;[Description("块大小")]public int BlockSize{get { return _blockSIze; }set { _blockSIze = value; }}private int _timeout = 10;[Description("溢出时间")]public int Timeout{get { return _timeout; }set { _timeout = value; }}PacketReader _packetReader = new PacketReader();PacketBuilder _packetBuilder = new PacketBuilder();public bool Get(string localFile, string RemoteFile, string Host){return Get(localFile, RemoteFile, Host, Mode, BlockSize, Timeout);}public bool Put(string localFile, string RemoteFile, string Host){return Put(localFile, RemoteFile, Host, Mode, BlockSize, Timeout);}public bool Get(string LocalFile, string RemoteFile, string Host,Modes Mode, int BlockSize, int Timeout){int recvLen, remoteFileSize = 0, buffer = BlockSize + 4;long bytesReceived = 0;BinaryWriter BWriter = new BinaryWriter(File.Open(LocalFile, FileMode.Create));OpCodes opCode = new OpCodes();IPHostEntry hInfo = Dns.GetHostEntry(Host);IPAddress address = hInfo.AddressList[0];IPEndPoint remoteEP = new IPEndPoint(address, 69);EndPoint localEP = (remoteEP);Socket UDPSock = new Socket(remoteEP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);// Create initial request and buffer for responsebyte[] sendData = _packetBuilder.Request(OpCodes.RRQ,RemoteFile, Mode, BlockSize, 0, Timeout);byte[] recvData = new byte[BlockSize + 4];UDPSock.ReceiveTimeout = Timeout * 1000;// Send request and wait for responseUDPSock.SendTo(sendData, remoteEP);recvLen = UDPSock.ReceiveFrom(recvData, ref localEP);// Get TIDremoteEP.Port = ((IPEndPoint)localEP).Port;// Invoke connected eventConnected.Invoke();while (true){// Read opcodeopCode = _packetReader.ReadOpCode(recvData);// DATA packetif (opCode == OpCodes.DATA){bytesReceived += recvLen - 4;// Invoke Transferring EventTransferring.Invoke(bytesReceived, remoteFileSize);for (int h = 4; h < recvLen; h++){BWriter.Write(recvData[h]);}sendData = _packetBuilder.Ack(recvData[2], recvData[3]);// Check if this packet is the lastif (recvLen < buffer){// Send final ACKUDPSock.SendTo(sendData, remoteEP);// Invoked TransferFinished EventTransferFinished.Invoke();break;}}// OACK packetelse if (opCode == OpCodes.OACK){remoteFileSize = _packetReader.ReadTransferSize(recvData);sendData = _packetBuilder.Ack(0, 0);}// ERROR packetelse if (opCode == OpCodes.ERROR){ErrorPacket transferError = _packetReader.ReadError(recvData);TransferFailed.Invoke(transferError.Code, transferError.Message);break;}// Send next packetUDPSock.SendTo(sendData, remoteEP);recvLen = UDPSock.ReceiveFrom(recvData, ref localEP);remoteEP.Port = ((IPEndPoint)localEP).Port;}BWriter.Close();UDPSock.Close();// Invoke Disconnected EventDisconnected.Invoke();return true;}public bool Put(string LocalFile, string RemoteFile, string Host,Modes Mode, int BlockSize, int Timeout){int[] block = new int[2];int bufferSize = BlockSize;long fileSize, bytesSent = 0;BinaryReader BReader = new BinaryReader(File.Open(LocalFile, FileMode.Open));FileInfo sendFile = new FileInfo(LocalFile);OpCodes opCode = new OpCodes();IPHostEntry hostInfo = Dns.GetHostEntry(Host);IPAddress address = hostInfo.AddressList[0];IPEndPoint remoteEP = new IPEndPoint(address, 69);EndPoint localEP = (remoteEP);Socket UDPSock = new Socket(remoteEP.AddressFamily, SocketType.Dgram, ProtocolType.Udp);// Retrieve filesize for tsize optionfileSize = sendFile.Length;// Create initial request and buffer for responsebyte[] sendData = _packetBuilder.Request(OpCodes.WRQ,RemoteFile, Mode, BlockSize, fileSize, Timeout);byte[] recvData = new byte[bufferSize];UDPSock.ReceiveTimeout = Timeout * 1000;// Send request and wait for responseUDPSock.SendTo(sendData, remoteEP);UDPSock.ReceiveFrom(recvData, ref localEP);//Get TIDremoteEP.Port = ((IPEndPoint)localEP).Port;// Invoke Connected EventConnected.Invoke();while (true){// Read opcodeopCode = _packetReader.ReadOpCode(recvData);// ACK packetif (opCode == OpCodes.ACK){block = _packetBuilder.IncrementBock(recvData, block);sendData = BReader.ReadBytes(bufferSize);bytesSent += sendData.Length;// Invoke Transferring EventTransferring.Invoke(bytesSent, fileSize);sendData = _packetBuilder.Data(sendData, block[0], block[1]);// Check if this packet is the lastif (sendData.Length < bufferSize + 4){// Send final data packet and wait for ackwhile (true){UDPSock.SendTo(sendData, remoteEP);UDPSock.ReceiveFrom(recvData, ref localEP);remoteEP.Port = ((IPEndPoint)localEP).Port;// Check the blocks and break free if equalif (_packetReader.CompareBlocks(sendData, recvData))break;}// Invoke TransferFinished EventTransferFinished.Invoke();break;}}// OACK packetelse if (opCode == OpCodes.OACK){sendData = BReader.ReadBytes(bufferSize);sendData = _packetBuilder.Data(sendData, 0, 1);bytesSent += sendData.Length - 4;// Invoke Transferring EventTransferring.Invoke(bytesSent, fileSize);if (fileSize == 0){// Invoke TransferFinished EventTransferFinished.Invoke();break;}else{// Check if this packet is the lastif (sendData.Length < bufferSize + 4){// Send final data packet and wait for ackwhile (true){UDPSock.SendTo(sendData, remoteEP);UDPSock.ReceiveFrom(recvData, ref localEP);remoteEP.Port = ((IPEndPoint)localEP).Port;// Check the blocks and break free if equalif (_packetReader.CompareBlocks(sendData, recvData))break;}// Invoke TransferFinished EventTransferFinished.Invoke();break;}}}else if (opCode == OpCodes.ERROR){ErrorPacket transferError = _packetReader.ReadError(recvData);TransferFailed.Invoke(transferError.Code, transferError.Message);break;}// Send next packetUDPSock.SendTo(sendData, remoteEP);UDPSock.ReceiveFrom(recvData, ref localEP);remoteEP.Port = ((IPEndPoint)localEP).Port;}BReader.Close();UDPSock.Close();// Invoke Disconnected EventDisconnected.Invoke();return true;}}
}

7、MainForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;namespace TftpTest
{public partial class MainForm : Form{private TftpClient tftpClient = new TftpClient();private delegate void ProgressBarDelegate(int Maximum, int Value);private delegate void TransferButtonDelegate(bool Enabled);public MainForm(){InitializeComponent();tftpClient.Connected += new TftpClient.ConnectedHandler(TftpClient_Connected);tftpClient.Transferring += new TftpClient.TransferringHandler(TftpClient_Transferring);tftpClient.TransferFailed += new TftpClient.TransferFailedHandler(TftpClient_TransferFailed);tftpClient.TransferFinished += new TftpClient.TransferFinishedHandler(TftpClient_TransferFinished);tftpClient.Disconnected += new TftpClient.DisconnectedHandler(TftpClient_Disconnected);}private void TftpClient_Connected(){TransferButtonDelegate tBtnDel = new TransferButtonDelegate(TransferBtnDelegateFunction);btnTest.Invoke(tBtnDel, false);Console.WriteLine("Connected");}private void TransferBtnDelegateFunction(bool Enabled){lock (btnTest){btnTest.Enabled = Enabled;}}private void TftpClient_Transferring(long BytesTransferred, long BytesTotal){if (BytesTotal != 0){ProgressBarDelegate progressBarDel = new ProgressBarDelegate(ProgressBarDelegateFunction);progressBarTftp.Invoke(progressBarDel,new object[2] { (int)(BytesTotal / 10), (int)(BytesTransferred / 10) });Console.Write("{0}/{1} Bytes Transferred\r", BytesTransferred, BytesTotal);}elseConsole.Write(".");}private void ProgressBarDelegateFunction(int Maximum, int Value){lock (progressBarTftp){try{progressBarTftp.Maximum = Maximum;progressBarTftp.Value = Value;}catch (Exception e) { Console.WriteLine(e.ToString()); }}}private void TftpClient_TransferFailed(short ErrorCode, string ErrorMessage){Console.WriteLine("Error {0}: {1}", ErrorCode, ErrorMessage);}private void TftpClient_TransferFinished(){ProgressBarDelegate progressBarDel = new ProgressBarDelegate(ProgressBarDelegateFunction);progressBarTftp.Invoke(progressBarDel, new object[2] { 0, 0 });Console.WriteLine("\nTransfer Finished");MessageBox.Show("Transfer Complete", "TFTP Client",MessageBoxButtons.OK, MessageBoxIcon.Information);}private void TftpClient_Disconnected(){TransferButtonDelegate tBtnDel = new TransferButtonDelegate(TransferBtnDelegateFunction);btnTest.Invoke(tBtnDel, true);Console.WriteLine("Disconnected\n");}private void btnTest_Click(object sender, EventArgs e){progressBarTftp.Value = 0;TransferOptions tOptions = new TransferOptions();//tOptions.LocalFilename = "D:\\Project\\QDRP3\\Sw\\QDRP\\QDRP\\bin\\Debug\\Case\\PLBIN.bin";tOptions.LocalFilename = "F:\\Test\\PLBIN.bin";tOptions.RemoteFilename = "PLBIN.bin";tOptions.Host = "10.11.9.62";//tOptions.Action = getRadio.Checked == true ? TransferType.Get : TransferType.Put;tOptions.Action = TransferType.Get;Thread tThread = new Thread((ParameterizedThreadStart)delegate (object ScanOptions){TransferOptions options = (TransferOptions)ScanOptions;if (options.Action == TransferType.Get)tftpClient.Get(options.LocalFilename,options.RemoteFilename,options.Host);elsetftpClient.Put(options.LocalFilename, options.RemoteFilename, options.Host);});tThread.IsBackground = true;tThread.Start(tOptions);}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/3576.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux论坛搭建

1.安装httpd服务 1.1安装httpd软件 [rootlocalhost yum.repos.d]# dnf install httpd 1.2.修改httpd的配置 [rootlocalhost yum.repos.d]# vim /etc/httpd/conf/httpd.conf 1.3.启动这个httpd服务,并查看它的状态 [rootlocalhost yum.repos.d]# systemctl start httpd [ro…

JavaEE——spring MVC请求处理

目录 主要目的&#xff1a; 1. Spring web 项目搭建 2. 添加依赖 3. 配置插件 4. 配置设置类 5. 编写controller层类 6. 编写测试的http请求 主要目的&#xff1a; 创建一个spring web项目&#xff1b; 创建控制类&#xff1b; 掌握如何配置MVC&#xff1b; 编写htt…

【机器学习-18】特征筛选:提升模型性能的关键步骤

一、引言 在机器学习领域&#xff0c;特征筛选是一个至关重要的预处理步骤。随着数据集的日益庞大和复杂&#xff0c;特征的数量往往也随之激增。然而&#xff0c;并非所有的特征都对模型的性能提升有所贡献&#xff0c;有些特征甚至可能是冗余的、噪声较大的或者与目标变量无关…

Django框架之python后端框架介绍

一、网络框架及MVC、MTV模型 1、网络框架 网络框架&#xff08;Web framework&#xff09;是一种软件框架&#xff0c;用于帮助开发人员构建Web应用程序和Web服务。它提供了一系列预先编写好的代码和工具&#xff0c;以简化开发过程并提高开发效率。网络框架通常包括以下功能…

常用组件(启停活动页面、活动之间传递信息、收发应用广播、操作后台服务)

启停活动页面 Activity的启动和结束 页面跳转可以使用startActivity接口&#xff0c;具体格式为startActivity(new Intent(this, 目标页面.class));。 关闭一个页面可以直接调用finish();方法即可退出页面。 Activity的生命周期 页面在安卓有个新的名字叫活动&#xff0c;因…

充电机是什么?其技术原理和行业应用

充电机是一种能够为电池充电的设备,通常由一个变压器和整流器组成。变压器将电网中的交流电转换为直流电,而整流器则将直流电转换为稳定的直流电,这种直流电可以被用来给电池充电。 充电机可以分为很多种不同类型,包括输入输出式、输入输出隔离式和车载充电机等。不同类型的充…

GoLand 2021.1.3 下载与安装

当前环境&#xff1a;Windows 8.1 x64 1 浏览器打开网站 https://www.jetbrains.com/go/download/other.html 找到 2021.1.3 版本。 2 解压 goland-2021.1.3.win.zip 到 goland-2021.1.3.win。 3 打开 bin 目录下的 goland64.exe&#xff0c;选择 Evaluate for free -- Evalu…

论文解读-面向高效生成大语言模型服务:从算法到系统综述

一、简要介绍 在快速发展的人工智能&#xff08;AI&#xff09;领域中&#xff0c;生成式大型语言模型&#xff08;llm&#xff09;站在了最前沿&#xff0c;彻底改变了论文与数据交互的方式。然而&#xff0c;部署这些模型的计算强度和内存消耗在服务效率方面带来了重大挑战&a…

ABS8-ASEMI新能源专用整流桥ABS8

编辑&#xff1a;ll ABS8-ASEMI新能源专用整流桥ABS8 型号&#xff1a;KBL410 品牌&#xff1a;ASEMI 封装&#xff1a;ABS-4 最大重复峰值反向电压&#xff1a;800V 最大正向平均整流电流(Vdss)&#xff1a;1A 功率(Pd)&#xff1a;小功率 芯片个数&#xff1a;4 引脚…

夜神、雷电、android studio手机模拟器资源占用情况

夜神、雷电、android studio手机模拟器内存资源占用情况 由于开发电脑只有16G内存&#xff0c;出于开发需要和本身硬件资源的限制&#xff0c;对多个手机模拟器进行了机器资源占用&#xff08;主要是内存&#xff09;的简单比较。 比较的模拟器包括&#xff1a; 1. Android S…

MATLAB 向量

MATLAB 向量 向量是一维数字数组。MATLAB允许创建两种类型的向量 行向量 列向量 行向量 行向量通过将元素集括在方括号中并使用空格或逗号定界元素来创建。 示例 r [7 8 9 10 11] MATLAB将执行上述语句并返回以下结果- r 7 8 9 10 11 列向量 列向量 通过将元素集括在方…

操作系统安全:Linux安全审计,Linux日志详解

「作者简介」&#xff1a;2022年北京冬奥会网络安全中国代表队&#xff0c;CSDN Top100&#xff0c;就职奇安信多年&#xff0c;以实战工作为基础对安全知识体系进行总结与归纳&#xff0c;著作适用于快速入门的 《网络安全自学教程》&#xff0c;内容涵盖系统安全、信息收集等…

区块链技术与应用学习笔记(10-11节)——北大肖臻课程

目录 10.分岔 ①什么是分叉&#xff1f; ②导致分叉的原因&#xff1f; ③在比特币新共识规则发布会会导致什么分叉&#xff1f; 什么是硬分叉&#xff1f; 硬分叉例子&#xff1f; 什么是软分叉&#xff1f; 软分叉和硬分叉区别&#xff1f; 软分叉实例 11.问答 转…

【从后端日志文件中过滤出sql语句】

从后端日志文件中过滤出sql语句 why?思路日志文件的格式 结果 why? 为什么会有这种需求&#xff1f;&#xff0c;mysql数据不小心被删了完全可以从备份数据恢复&#xff0c;或者从binlog中恢复&#xff0c;但是如果前面这两种方法没办法处理&#xff08;没有备份数据库文件、…

科技云报道:走入商业化拐点,大模型“开箱即用”或突破行业困局

科技云报道原创。 大模型加速狂飙&#xff0c;AI商业化却陷入重重困境。 一方面&#xff0c;传统企业不知道怎么将AI融入原始业务&#xff0c;另一方面&#xff0c;AI企业难以找到合适的商业化路径。 纵观海外AI玩家&#xff0c;已经有许多企业趟出了自己的商业化道路。 微…

59、回溯-括号生成

思路&#xff1a; 括号是成对出现&#xff0c;首先左括号可以放n个&#xff0c;右括号也可以放n个。如果当前左括号放了3了&#xff0c;右括号放了4个&#xff0c;错了&#xff0c;如果左括号放了5个&#xff0c;右括号放了4个。可以&#xff0c;继续放右括号即可。所以可以设…

贪吃蛇项目实践!(上)

大家好&#xff0c;今天我带着大家从0构建起贪吃蛇项目的高楼大厦~ 要实现这个游戏&#xff0c;我们需要实现哪些功能呢&#xff1f; 实现基本的功能&#xff1a; • 贪吃蛇地图绘制 • 蛇吃⻝物的功能&#xff08;上、下、左、右⽅向键控制蛇的动作&#xff09; • 蛇撞墙死…

matlab保存示波器数据

再重新运行一下示波器 然后就可以在工作区看见&#xff08;这里没有运行所以没有&#xff09; 将保存到文件夹中方便后续绘图

华为云FunctionGraph构建高可用系统的实践

导语 每年&#xff0c;网上都会报道XXX系统异常不可用&#xff0c;给客户带来巨大的经济损失。云服务的客户基数更大&#xff0c;一旦出现问题&#xff0c;都将给客户和服务自身带来极大影响。本文将基于华为云FunctionGraph自身的实践&#xff0c;详细介绍如何构建高可用的Se…

权威认证!瀚高股份IvorySQL通过强制性国标GB18030-2022最高级别认证

近日&#xff0c;GB 18030-2022《信息技术 中文编码字符集》应用推广大会暨“汉字守护计划”成果发布会在京召开。瀚高股份开源关系型数据库IvorySQL通过 GB 18030-2022《信息技术 中文编码字符集》强制性国家标准测试&#xff0c;达到最高实现级别&#xff08;3级&#xff09;…