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

时间:2014-02-23 14:59:21

标签: c# networking tcpclient tcplistener networkstream

我正在开发一个客户端 - 服务器项目,它包含一个客户端应用程序和一个服务器应用程序。客户端应用程序可以将文件发送到服务器应用程序,服务器应用程序接收该文件并将其写入其文件夹中。 projectworks,但只有一个长度为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;
}

2 个答案:

答案 0 :(得分:1)

撰写时,您没有使用recieved的值。

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

答案 1 :(得分:1)

执行a.Write()时,必须使用nws.Read()的结果,如下所示:

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

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