本文介绍了UDP文件传输问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在尝试创建一个点对点应用程序来发送文件,然后我将大文件分成小块。我首先发送文件信息,包括文本格式的文件信息,没有问题,但发送字节在客户端的某些时刻停止,我把它放在标有BOLD的代码片段中。我不知道数据包是丢失还是代码不同步。这是两个类的代码片段,这里是我从客户端读取文件的代码 提前感谢 class DownloadClientHi, I am trying to create a peer to peer application to send files , then I divide big files to small chunks.  I send first the file information including name and size in text format with no problems but sending bytes stops at certain moments from the client side , I have it down in the code snippet marked in BOLD. I don't know if the packets are lost or if the code is not synchronized. Here is the code snippets for both classes ,here is the code I am doing to read the file from the clientThanks in advanceclass DownloadClient { private const int MAX_BUFFER_SIZE = 10240;private const int MAX_BUFFER_SIZE = 10240; Byte [] inputToBeSent = new Byte [256];Byte[] inputToBeSent = new Byte[256]; UdpClient udpClient;UdpClient udpClient; IPEndPoint remoteIpEndPoint;IPEndPoint remoteIpEndPoint; IPHostEntry remoteHostEntry;IPHostEntry remoteHostEntry; Socket DownloadSocket;Socket DownloadSocket; public int sendLine( string line)public int sendLine(string line) { inputToBeSent = System.Text。 编码 .ASCII.GetBytes(line.ToCharArray());inputToBeSent = System.Text.Encoding.ASCII.GetBytes(line.ToCharArray()); int nBytesSent = udpClient.Send(inputToBeSent,inputToBeSent.Length);int nBytesSent = udpClient.Send(inputToBeSent, inputToBeSent.Length); return nBytesSent;return nBytesSent;} public void sendBytes( byte [] data)public void sendBytes(byte[] data) { udpClient.Send(data,data.Length);udpClient.Send(data, data.Length);} public byte [] Receive()public byte[] Receive() { byte [] buf = new byte [14];byte[] buf = new byte[14]; buf = udpClient.Receive( ref remoteIpEndPoint);buf = udpClient.Receive(ref remoteIpEndPoint); return buf;return buf;} public string ReceiveLine()public string ReceiveLine() { return System.Text。 编码 .ASCII.GetString(Receive());return System.Text.Encoding.ASCII.GetString(Receive());} public void Connect( string remoteUserIP, int _remoteUserPort)public void Connect(string remoteUserIP, int _remoteUserPort) { udpClient = new UdpClient ();udpClient = new UdpClient(); udpClient.Connect( IPAddress 。解析( " 127.0.0.1" ),9050);udpClient.Connect(IPAddress.Parse("127.0.0.1"), 9050); // MessageBox.Show (files.Length.ToString());// MessageBox.Show(files.Length.ToString()); 的 // for(int i = 0;我< files.Length; i ++)//for (int i = 0; i < files.Length; i++) // {//{ string fileName = "EG7.pdf" ;string fileName = "EG7.pdf"; DownloadSocket.Send( 编码 .ASCII.GetBytes( " getFile#" + " user" + "#" + fileName));DownloadSocket.Send(Encoding.ASCII.GetBytes("getFile#" + "user" + "#" + fileName)); // sendLine(" getFile#" +" user" +& QUOT;#" + fileName);//sendLine("getFile#" + "user" + "#" + fileName); // string tmp = ReceiveLine();//string tmp = ReceiveLine(); Byte [] received = new 字节 [512];Byte[] received = new Byte[512]; String tmp = ReceiveLine();String tmp = ReceiveLine(); if (tmp.StartsWith( "错误" ))if (tmp.StartsWith("Error")) { int downloaded = 0;int downloaded = 0; int read = 0; int read = 0; byte [] stream = null ;byte[] stream = null; 尝试try { while (已下载< nbBytes)while (downloaded < nbBytes) { if (nbBytes - 已下载> MAX_BUFFER_SIZE)if (nbBytes - downloaded > MAX_BUFFER_SIZE) { stream = new byte [MAX_BUFFER_SIZE];stream = new byte[MAX_BUFFER_SIZE];} elseelse { stream = new byte [nbBytes - 已下载];stream = new byte[nbBytes - downloaded];}已下载+ = udpClient.Available;downloaded += udpClient.Available; stream = udpClient.Receive( ref remoteIpEndPoint) ;stream = udpClient.Receive(ref remoteIpEndPoint);}} catch ( 例外 e)catch (Exception e) { MessageBox .Show(e.Message);MessageBox.Show(e.Message);} MessageBox .Show( " done receving" );MessageBox.Show("done receving"); // byte [] stream = br.ReadBytes(size);//byte[] stream = br.ReadBytes(size);   }  public void ProcessDownload()public void ProcessDownload() { while ( true )while (true) { string request = readLine();string request = readLine(); MessageBox .Show(request);MessageBox.Show(request); StringBuilder response = new StringBuilder ();StringBuilder response = new StringBuilder(); if (request.IndexOf( " getFile#" )> = 0)if (request.IndexOf("getFile#") >= 0) { string [] tokens = request.Split ( '#' );string[] tokens = request.Split('#'); string user =令牌[1];string user = tokens[1]; string filename = tokens [2];string filename = tokens[2]; 尝试try { FileInfo fi = new FileInfo (filename);FileInfo fi = new FileInfo(filename); FileStream fileIn = fi.OpenRead();FileStream fileIn = fi.OpenRead(); BinaryReader br = new BinaryReader (fileIn);BinaryReader br = new BinaryReader(fileIn); int filesize =(( int )fi.Length);int filesize = ((int)fi.Length); response.Append( " file#" + filesize);response.Append("file#" + filesize); sendLine(response.ToString());sendLine(response.ToString()); int bytes_read = 0,n = 0;int bytes_read = 0, n = 0; byte [] stream;byte[] stream; // FileStream fs = new FileStream(" test.pdf",FileMode.Create);// FileStream fs = new FileStream("test.pdf", FileMode.Create); dodo { if (filesize - bytes_read> MAX_BUFFER_SIZE)if (filesize - bytes_read > MAX_BUFFER_SIZE) stream = new byte [MAX_BUFFER_SIZE];stream = new byte[MAX_BUFFER_SIZE]; elseelse stream = new byte [filesize - bytes_read];stream = new byte[filesize - bytes_read]; //寻找未读取的下一个字节//seek the next byte not read fileIn.Seek(bytes_read, SeekOrigin .Begin);fileIn.Seek(bytes_read, SeekOrigin.Begin); n = fileIn.Read(stream,0,stream.Length);n = fileIn.Read(stream, 0, stream.Length); / * n = fileIn.read(stream,byte s_read,MAX_BUFFER_SIZE); * //* n = fileIn.read(stream, bytes_read, MAX_BUFFER_SIZE);*/ bytes_read + = n;bytes_read += n; //发送字节//send bytes sendBytes(stream);sendBytes(stream); / / fs.Write(stream,0,stream.Length);// fs.Write(stream, 0, stream.Length); // fs.Close();//fs.Close(); // MessageBox.Show(" \tn ==" + n);//MessageBox.Show("\tn ==" + n); Thread .Sleep(40);Thread.Sleep(40);} 而 ((bytes_read< filesize )&&(n!= -1));while ((bytes_read < filesize) && (n != -1)); // fs.Close();//fs.Close(); MessageBox .Show( " Done sending" );MessageBox.Show("Done sending");} catch ( 例外 e)catch (Exception e) { MessageBox .Show(e.Message);MessageBox.Show(e.Message);} }} //}// } sendLine( "Done \ n" );sendLine("Done\n");}}推荐答案 UDP不保证交付或包顺序。 这意味着要发送这样的文件,你需要在每个包含序列号的数据包上都有一个标题,并有一些确认系统来确认传递并在必要时重新发送部分文件。 通常情况下,当需要这些时,它表明您应该使用TCP而不是UDP。 -SteveUDP does not guarantee delivery or packet order.This means that to send a file like this, you need to have a header on every packet with a sequence number, and have some kind of acknowledgement system to confirm delivery and re-send parts of the file as necessary.Usually, when these are required, it's an indication that you should be using TCP instead of UDP.        -Steve 这篇关于UDP文件传输问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 01:00