EventSource需要一个特定的 formatonerror
,如果流与该格式不匹配,则会引发- 一组由 a 分隔的字段/值对:
行,每行以换行符结尾:
field: value
field: value
field
可以是data
, event
, id
,retry
中的一个或空的评论(将被 EventSource 忽略)。
data
可以跨越多行,但每行必须以data:
每个事件触发器必须以双换行符结尾
data: 1
data: second line of message
data: 2
data: second line of second message
注意:如果你是用 VB.NET 编写的,你不能使用\n
转义序列来编写换行符;你必须使用vbLf
or Chr(10)
。
顺便说一句,EventSource 应该保持与服务器的开放连接。来自MDN(重点是我的):
EventSource接口用于接收服务器发送的事件。它通过 HTTP 连接到服务器并以文本/事件流格式接收事件,而无需关闭连接。
一旦控制从 MVC 控制器方法中退出,结果将被打包并发送到客户端,并关闭连接。EventSource 的一部分是客户端将尝试重新打开连接,该连接将再次被服务器立即关闭;由此产生的close -> reopen
循环也可以在这里看到。
该方法不应退出该方法,而应具有某种循环,该循环将连续写入Response
流。
VB.NET 中的示例
Imports System.Threading
Public Class HomeController
Inherits Controller
Sub Message()
Response.ContentType= "text/event-stream"
Dim i As Integer
Do
i += 1
Response.Write("data: DateTime = " & Now & vbLf)
Response.Write("data: Iteration = " & i & vbLf)
Response.Write(vbLf)
Response.Flush
'The timing of data sent to the client is determined by the Sleep interval (and latency)
Thread.Sleep(1000)
Loop
End Sub
End Class
C# 中的示例
客户端:
<input type="text" id="userid" placeholder="UserID" /><br />
<input type="button" id="ping" value="Ping" />
<script>
var es = new EventSource('/home/message');
es.onmessage = function (e) {
console.log(e.data);
};
es.onerror = function () {
console.log(arguments);
};
$(function () {
$('#ping').on('click', function () {
$.post('/home/ping', {
UserID: $('#userid').val() || 0
});
});
});
</script>
服务器端:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Web.Mvc;
using Newtonsoft.Json;
namespace EventSourceTest2.Controllers {
public class PingData {
public int UserID { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
}
public class HomeController : Controller {
public ActionResult Index() {
return View();
}
static ConcurrentQueue<PingData> pings = new ConcurrentQueue<PingData>();
public void Ping(int userID) {
pings.Enqueue(new PingData { UserID = userID });
}
public void Message() {
Response.ContentType = "text/event-stream";
do {
PingData nextPing;
if (pings.TryDequeue(out nextPing)) {
Response.Write("data:" + JsonConvert.SerializeObject(nextPing, Formatting.None) + "\n\n");
}
Response.Flush();
Thread.Sleep(1000);
} while (true);
}
}
}