从服务器下载文件后转为无响应

问题描述:

这是一件非常奇怪的事情。从服务器下载文件后转为无响应

我创建了一个客户端和一个服务器来上传和下载文件。上传时,我可以上传大量文件,但没有问题,但是当我下载文件时,客户端转向不响应,并且不会显示MessageBox.show("Downloaded");它的第一个匹配项,以查看此内容:D。

使用时,使该问题的代码:

private void button3_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     String fileToDownload = filePathDownload.Text; 


     TcpClient clientSocket = new TcpClient(serverIPDownload.Text, 8880); 
     NetworkStream networkStream = clientSocket.GetStream(); 
     ASCIIEncoding asci = new ASCIIEncoding(); 
     byte[] b = asci.GetBytes(fileToDownload + "?"); 
     byte[] bb = asci.GetBytes("Download?"); 
     int thisRead = 0; 
     int blockSize = 1024; 
     Byte[] dataByte = new Byte[blockSize]; 

     networkStream.Write(bb, 0, bb.Length); 
     networkStream.Flush(); 
     networkStream.Write(b, 0, b.Length); 
     networkStream.Flush(); 

     using (FileStream fileStream = new FileStream(
      "C:/Users/Laptop/Documents/Downloads/" + fileToDownload, 
      FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) 
     { 
      while (true) 
      { 
       thisRead = networkStream.Read(dataByte, 0, blockSize); 

       fileStream.Write(dataByte, 0, thisRead); 
       if (thisRead == 0) break; 

      } 
      MessageBox.Show("File Downloaded"); 
      fileStream.Close(); 
     } 
    } 
    catch (Exception ex) { MessageBox.Show(ex.Message); } 
} 

感谢。这可能不是主题,但它是我面临的问题。

您的代码似乎没问题,所以我怀疑问题出在您正在阅读的下载方法中。

此外,我会亲自将fileStream.Write声明之前的循环终止(if (thisRead == 0) break;)移动。

而对于产品代码,我会添加某种超时限制,以免最终陷入无限循环。