Search code examples
c#tcptcpclienttcplistener

Sending Mp3 File via tcpserver to a client


i have a tcp client as below:

 public static void RunStream()
    {
        Console.WriteLine("Starting Stream...");
        TcpListener listen = new TcpListener(IPAddress.Parse("127.0.0.1"), 13000);
        listen.Start();
        while (true)
        {
            Console.Write("Waiting for a connection... ");
            Socket socket = listen.AcceptSocket();

            if (socket.Connected)
            {
                SendFile(socket);
                socket.Disconnect(false);
            }
        }
    }
    public static void SendFile(Socket socket)
    {
        NetworkStream netstream = new NetworkStream(socket);
        StreamWriter writer = new StreamWriter(netstream);
        FileStream fileStream = File.Open("file_example_MP3_700KB.mp3", FileMode.Open, FileAccess.Read, FileShare.Read);
        fileStream.CopyTo(netstream);
        netstream.Flush();
        netstream.Close();

    }

    static void Main(string[] args)
    {
        RunStream();
    }

and a client that reads and save the stream (which contains the mp3 file) from the server like this:

 static void Main(string[] args)
    {


        TcpClient client = new TcpClient("127.0.0.1", 13000);
        
        byte[] bytes = new byte[2100000];
        var stream = client.GetStream();
        int i;
        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            stream.Write(bytes, 0, i);
        }
        File.WriteAllBytes("test.mp3", bytes);
        stream.Flush();
        client.Close();           
    }

the issue is that i got only a snippet of the original mp3, for example if the origianl file has a 24 seconds duration i only get the first 5-8


Solution

  • bro in client you wrote stream.Read(bytes, 0, bytes.Length) this mean you rewrite array every time reading data
    and you using a big array for save your data and if you send a big file this will make problem
    its better code like this bro :

        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("127.0.0.1", 13000);
    
            var stream = client.GetStream();
            byte[] buff = new byte[1024]; //you can change length later, bigger arrays have more reading speed but give more ram
            FileStream filestream = new FileStream("test.mp3", FileMode.Create);
            while (stream.Length > stream.Position)
            {
                int readLength = stream.Read(buff, 0, buff.Length);
                filestream.Write(buff, 0, readLength);
            }
            stream.Flush();
            client.Close();
        }