C#实现TFTP客户端

2024-04-25 23:20

本文主要是介绍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);}}
}

这篇关于C#实现TFTP客户端的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/936077

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

用命令行的方式启动.netcore webapi

用命令行的方式启动.netcore web项目 进入指定的项目文件夹,比如我发布后的代码放在下面文件夹中 在此地址栏中输入“cmd”,打开命令提示符,进入到发布代码目录 命令行启动.netcore项目的命令为:  dotnet 项目启动文件.dll --urls="http://*:对外端口" --ip="本机ip" --port=项目内部端口 例: dotnet Imagine.M

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、