【问题标题】:ASP.NET MVC 5 response streaming not working. Only staging/production environmentASP.NET MVC 5 响应流不起作用。仅登台/生产环境
【发布时间】:2017-08-12 05:08:26
【问题描述】:

我正在尝试使用 http 持续将数据流式传输到客户端。该代码在 localhost 上工作,但在 IIS 或 Apache 下(在 Linux 上使用单声道)下的生产环境中不起作用。

当代码在生产服务器上时,它不会刷新任何内容,直到我关闭连接。它确实可以在本地主机上正常工作。

 public class EventsStreamController : Controller
    {
    static EventsStreamController()
    {
        ConcurrentDictionary = new ConcurrentDictionary<uint, Client>();
    }

    private static ConcurrentDictionary<uint, Client> ConcurrentDictionary { get; }

    /// <summary>
    /// http://localhost:42022/EventsStream/SendMesaage/?pollSessionID=2&message=cats
    /// </summary>
    [HttpGet]
    public async Task Connect(uint pollSessionID)
    {
        var httpResponse = this.Response;

        httpResponse.BufferOutput = false;

        var client = new Client(pollSessionID);

        if (!ConcurrentDictionary.TryAdd(client.ClientId, client))
        {
            throw new ApplicationException("The client is already in the dictionary.");
        }

        while (true)
        {
            await Task.Delay(2000);

            string message;

            if (client.Messages.TryDequeue(out message))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(message);

                httpResponse.BinaryWrite(buffer);
                httpResponse.Flush();

                if (message == "close")
                {
                    break;
                }
            }
        }
    }

    /// <summary>
    /// http://localhost:42022/EventsStream/connect/?pollSessionID=2
    /// </summary>
    [HttpGet]
    public ActionResult SendMesaage(uint pollSessionID, string message)
    {
        Client client;
        if (!ConcurrentDictionary.TryGetValue(pollSessionID, out client))
        {
            throw new ApplicationException("Client not found.");
        }

        client.Messages.Enqueue(message);

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }

    public class Client
    {
        public Client(uint clientId)
        {
            this.ClientId = clientId;
            this.Messages = new ConcurrentQueue<string>();
        }

        public uint ClientId { get; set; }

        public ConcurrentQueue<string> Messages { get; }
    }
}

我使用TaskCompletionSource 通知等待请求它必须将数据流式传输到客户端,但为了简单起见,我将其更改为每 2 秒检查一次。(还在服务器上测试过,仍然无法正常工作.)

【问题讨论】:

    标签: asp.net asp.net-mvc async-await streaming


    【解决方案1】:

    您需要发送块,并用Transfer-Encoding: chunked HTTP 标头指示它。

    https://www.codeproject.com/Articles/648526/All-about-http-chunked-responses

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-14
      • 2019-01-04
      • 2021-08-02
      • 2023-03-25
      • 2015-05-10
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多