无法在tcp客户端服务器中接收完整文件

时间:2014-11-04 08:55:01

标签: c# .net sockets memorystream ftp-client

以下是我用于读取mp4文件并发送到客户端的服务器代码

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Any, 3400);
sock.Bind(ep);
sock.Listen(10);
sock = sock.Accept();
FileStream fs = new FileStream(@"E:\Entertainment\Songs\Video song\song.mp4",FileMode.Open);      
BinaryReader br = new BinaryReader(fs);

byte[] data = new byte[fs.Length];
br.Read(data, 0, data.Length);
sock.Send(data);
fs.Close();
sock.Close(); 

以下是客户端代码

sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3400);
sock.Connect(ep);
MemoryStream ms = new MemoryStream();             
int size = 3190551; // I know the file size is about 30 mb
int rec;
while (size > 0)
{
        byte[] buffer;
        if (size < sock.ReceiveBufferSize)
        {
            buffer = new byte[size];
        }
        else
        {
            buffer = new byte[sock.ReceiveBufferSize];
        }
        rec = sock.Receive(buffer, 0, buffer.Length, 0);
        size = size - rec;
        ms.Write(buffer, 0, buffer.Length);                
}

byte[] data = ms.ToArray();
FileStream fs = new FileStream("E:/song.mp4",FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs)
bw.Write(data);
fs.Close();
sock.Close();

**最后我只是得到3到4 MB之间的数据....我对socket编程很新,我不知道问题出在哪里......无论是发送端还是接收端!!! !看起来我只是从服务器端收到一大块数据**

1 个答案:

答案 0 :(得分:0)

我认为问题出在这里

int size = 3190551; // I know the file size is about 30 mb

您正在阅读 3190551 字节 3.04mb 而非 30mb 。 尝试在邮件开头发送文件的长度,以便客户端知道应该从服务器获取多少字节。