如何使用自己的httpllistener向客户端发送文件

本文关键字:文件 客户端 何使用 自己的 httpllistener | 更新日期: 2023-09-27 18:07:09

我搜索了很多关于使用自托管的HTTP侦听器将文件从控制台应用程序发送到托管在ASP上的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() + @"'1.mp3");
        // res.ContentType = "text/plain";
         return res.WriteAsync("Hello, World!");
    });
}

这是一个自己的启动类,用来处理HTTP请求

如何使用自己的httpllistener向客户端发送文件

这里有一个完整的教程,它将涵盖你所有的需求,基本上是为了节省你的时间,如果你想发送一个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");
}

我建议你深入研究这篇文章,了解整个过程,看看它是否适合你的解决方案。