1

I've googled a lot about sending a file from a console application using an own HTTP listener self-hosted to a web application that hosted on ASP.NET MVC5 I've found a method in response named res.SendFileAsync, but I don't know how to use it. Here's my code:

public void Configuration(IAppBuilder app)
{
     app.UseHandlerAsync((req, res) =>
    {
        Console.Clear();
        foreach (var item in req.Headers)
        {
            Console.WriteLine(item.Key + ":" );
            foreach (var item1 in item.Value)
            {
                Console.Write(item1);
            }
        }
        //res.Headers.AcceptRanges.Add("bytes");
        //result.StatusCode = HttpStatusCode.OK;
        //result.Content = new StreamContent(st);
        //result.Content.Headers.ContentLength = st.Length;

        res.Headers.Add("ContentType" ,new string[]{"application/octet-stream"});
         res.SendFileAsync(Directory.GetCurrentDirectory() + @"\1.mp3");
        // res.ContentType = "text/plain";
         return res.WriteAsync("Hello, World!");
    });
}

This is an own startup class that handles HTTP requests.

1 Answer 1

0

There is a full tutorial here which will cover all of your needs, basically to save you time, if you want to send a byte[] to all your clients (which is how you should send a file) it should look like this:

static void Main(string[] args) {
    //---listen at the specified IP and port no.---
    Console.WriteLine("Listening...");
    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT_NO));
    serverSocket.Listen(4); //the maximum pending client, define as you wish
    serverSocket.BeginAccept(new AsyncCallback(acceptCallback), null);      

    //normally, there isn't anything else needed here
    string result = "";
    do {
        result = Console.ReadLine();
        if (result.ToLower().Trim() != "exit") {
            byte[] bytes = null;
            //you can use `result` and change it to `bytes` by any mechanism which you want
            //the mechanism which suits you is probably the hex string to byte[]
            //this is the reason why you may want to list the client sockets
            foreach(Socket socket in clientSockets)
                socket.Send(bytes); //send everything to all clients as bytes
        }
    } while (result.ToLower().Trim() != "exit");
}

I'd recommend you to delve deeper into the post and understand the entire process, see if it fits your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.