我尝试使用http不断地将数据流式传输到客户端。该代码适用于localhost,但在IIS或Apache(在Linux上使用mono)上的生产中不起作用。
当代码在生产服务器上时,在关闭连接之前它不会刷新任何内容。它确实在localhost上工作。
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秒检查一次。(还测试了在服务器上,仍然没有&# 39;工作。)
答案 0 :(得分:0)
您需要发送数据块,并使用Transfer-Encoding: chunked
HTTP标头指示它。
https://www.codeproject.com/Articles/648526/All-about-http-chunked-responses