【问题标题】:How to send a file to clients using owin httplistener?如何使用 owin httplistener 向客户端发送文件?
【发布时间】:2015-11-02 17:08:06
【问题描述】:

我在 Google 上搜索了很多关于使用自己的 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() + @"\1.mp3");
        // res.ContentType = "text/plain";
         return res.WriteAsync("Hello, World!");
    });
}

这是一个处理 HTTP 请求的自己的启动类。

【问题讨论】:

    标签: c# owin httplistener


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      相关资源
      最近更新 更多