如何使用 owin httplistener 向客户端发送文件?

How to send a file to clients using owin httplistener?

我在谷歌上搜索了很多关于使用自托管的 HTTP 侦听器从控制台应用程序发送文件到托管在 ASP.NET MVC5 上的 Web 应用程序的信息,我找到了一个名为 res.SendFileAsync,但是不知道怎么用。这是我的代码:

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() + @".mp3");
        // res.ContentType = "text/plain";
         return res.WriteAsync("Hello, World!");
    });
}

这是处理 HTTP 请求的自己的初创公司class。

有一个完整的教程 ,它将涵盖您的所有需求,基本上是为了节省您的时间,如果您想向所有客户发送 byte[](这是您应该发送文件)它应该是这样的:

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");
}

我建议您深入研究 post 并了解整个过程,看看它是否适合您的解决方案。