通过网络发送文件 - 缓冲区大小大于 2 不可能



我正在处理一个客户端-服务器项目,其中包含一个客户端-应用程序和一个服务器-应用程序。客户端应用程序可以将文件发送到服务器应用程序,服务器应用程序接收此文件并将其写入其文件夹中。该项目有效,但仅使用长度为 2 的(缓冲区)字节数组。

客户端应用程序和服务器应用程序都使用长度为 2 的字节数组。如果我选择更大的大小,例如 1024,则我会遇到问题,即服务器应用程序中收到的文件与客户端的原始文件的大小不同。

客户:

Byte[] fileBytes = new Byte[2];
long count = filesize;
while (count > 0) 
{
    int recieved = a.Read(fileBytes, 0, fileBytes.Length);
    a.Flush();
    nws.Write(fileBytes, 0, fileBytes.Length);
    nws.Flush();
    count -= recieved;
}

服务器:

long count = filesize;
Byte[] fileBytes = new Byte[2];
var a = File.OpenWrite(filename);
while (count > 0) 
{
    int recieved = nws.Read(fileBytes, 0, fileBytes.Length);
    nws.Flush();
    a.Write(fileBytes, 0, fileBytes.Length);
    a.Flush();
    count -= recieved;
}

您必须使用 nws 的结果。当你做 a.Write() 时 Read(),像这样:

int received = nws.Read(...);
a.Write(fileBytes, 0, received);

如果您不这样做,它确实会写入完整的缓冲区,而不仅仅是您收到的内容。

您在编写时没有使用 recieved 的值。

您可能希望切换到更高级别的解决方案,例如 HTTP 或 FTP。套接字编程非常困难且容易出错。

最新更新