C# Httpresponse gives Unable to write data to the transport connection: Broken pipe

0

I have done this little piece of code on a console app, to stream a file or to simulate a stream of data over HTTP by chunk

            var musicFile = "music.mp3";
            var imageFile = "image.mp3";

            var prefixes = new List<string>() { "http://*:8888/" };
            HttpListener server = new HttpListener();

            foreach (string s in prefixes)
            {
                server.Prefixes.Add(s);
            }

            server.Start();

            System.Console.WriteLine("Listening...");

            var context = server.GetContext();

            var response = server.GetContext().Response;

            //response.ContentType = "image/jpeg";
            response.ContentType = "audio/mpeg";
            response.SendChunked = true;

            const int chunkSize = 1024;
            using (var file = File.OpenRead(path))
            {
                int bytesRead;
                var buffer = new byte[chunkSize];
                while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
                {
                    try
                    {
                        response.OutputStream.Write(buffer, 0, bytesRead);
                        response.OutputStream.Flush();
                        
                        System.Console.WriteLine("Chunk sent.");
                    }
                    catch (System.Exception ex)
                    {
                        System.Console.WriteLine($"{ex.Message}");
                    }
                }
            }

            context.Response.Close();

Hello everyone This works perfectly when I send an 10mb image, but it throw an exception when I use a mp3 file or a wav file.

Unhandled exception. System.Net.HttpListenerException (0x80131620): Unable to write data to the transport connection: Broken pipe. at System.Net.HttpResponseStream.InternalWrite(Byte[] buffer, Int32 offset, Int32 count) at System.Net.HttpResponseStream.WriteCore(Byte[] buffer, Int32 offset, Int32 size) at System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)

Any help ? Thank you.

EDIT: I tested on the same machine and on lan, with Chrome and Safari.

c#
http
stream
chunks
broken-pipe
asked on Stack Overflow Sep 21, 2020 by M.Nemo • edited Sep 21, 2020 by M.Nemo

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0