TCP客户端在我尝试检索服务器上的文件时卡在读取状态



我制作了一个程序,将文件发送到另一台计算机进行视频编码。文件发送工作。但是当我取消注释服务器的"下载"功能以将文件检索到服务器时,客户端卡在读取(客户端"下载"功能)时。

客户:

static byte[] DownloadHASH(NetworkStream stream)
{
        byte[] check = new byte[32];
        stream.Read(check, 0, 32);
        return check;
}

static string Download(NetworkStream stream)
{
        int recByte = 0;
        byte[] buffer = new byte[1024];
        string tempFile = string.Format(@"{0}.mkv", Guid.NewGuid());
        FileStream fstream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
        Guid.NewGuid();
        while ((recByte = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fstream.Write(buffer, 0, recByte);
        }
        fstream.Close();
        return tempFile;
 }
 static void UpLoad(NetworkStream stream, string file) {
        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
        byte[] bytes = new byte[1024];
        int sendBytes = 0;
        int offset = 0;
        while ((sendBytes = fs.Read(bytes, offset, bytes.Length)) > 0)
        {
            stream.Write(bytes, 0, sendBytes);
        }
  }

服务器:

  FileStream fs = new FileStream(currentOp.file, FileMode.Open, FileAccess.Read);
  stream.Write(currentOp.checksum, 0 , currentOp.checksum.Length);
  byte[] bytes = new byte[1024];
  int sendBytes = 0;
  int offset = 0;
  while ((sendBytes = fs.Read(bytes, offset, bytes.Length)) > 0)
  {
      stream.Write(bytes, 0, sendBytes);
  }
  fs.Close();
  //Download(stream);
  void Download(NetworkStream stream)
  {
        int recByte = 0;
        byte[] buffer = new byte[1024];
        string tempFile = string.Format(@"{0}.mp4", Guid.NewGuid());
        FileStream fstream = new FileStream(tempFile, FileMode.Create, FileAccess.Write);
        Guid.NewGuid();
        while ((recByte = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fstream.Read(buffer, 0, recByte);
        }
        fstream.Close();
   }

我不知道为什么会附加这个。有人可以帮助我吗?

程序从流中读取数据,直到读取 0 个字节:

while ((recByte = stream.Read(buffer, 0, buffer.Length)) > 0)

但是,NetworkStream仅在另一端关闭连接时返回 0。您有两种选择可以解决此问题:

  • 发送完所有数据后关闭另一端的流,或者
  • 以消息格式包装数据,例如,首先将数据的大小作为固定大小的消息发送,然后精确地发送那么多字节,以便客户端知道何时完成文件下载

最新更新