first commit
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
using JSMachine.WMS.Business.SSE;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Text;
|
||||
|
||||
namespace JSMachine.WMS.WebHost.Controllers
|
||||
{
|
||||
/// <summary>
|
||||
/// 用于向前端网站推送消息
|
||||
/// </summary>
|
||||
[Route("api/sse")]
|
||||
public class SseController: ControllerBase
|
||||
{
|
||||
[HttpGet("connect")]
|
||||
public async Task Connect()
|
||||
{
|
||||
var response = Response;
|
||||
response.Headers.Append("Content-Type", "text/event-stream");
|
||||
response.Headers.Append("Cache-Control", "no-cache");
|
||||
response.Headers.Append("Connection", "keep-alive");
|
||||
|
||||
// 记录客户端连接(用于后续推送消息)
|
||||
ClientConnection client = new()
|
||||
{
|
||||
Response = response,
|
||||
ClientId = Guid.NewGuid().ToString()
|
||||
};
|
||||
SseEngine.AddClient(client);
|
||||
|
||||
// 保持连接,直到客户端断开
|
||||
while (!response.HttpContext.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(1000); // 防止 CPU 占用过高
|
||||
}
|
||||
|
||||
// 客户端断开时移除
|
||||
SseEngine.RemoveClient(client);
|
||||
}
|
||||
|
||||
[HttpPost("send")]
|
||||
public IActionResult SendMessage([FromBody] string message)
|
||||
{
|
||||
// 向所有连接的客户端推送消息
|
||||
SseEngine.BrodCast(message);
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user