Search code examples
c#.netsocketsmemorystreamftp-client

unable to receive full file in tcp client server


Here is my server code for reading a mp4 file and sending to the client

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(); 

Here is the client code

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();

**At the end i just get the data in between 3 to 4 mb.... im new to socket programming and I don't know where the problem is... whether its sending side or receiving !!!! it looks like I just receive a single chunk of data from the server side **


Solution

  • I think the problem is here

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

    you are reading just 3190551 byte which is 3.04mb not 30mb. try to send length of your file at the beginning of your message so client will know how many bytes it should get from server.