Javascript 服务器与ASP.Net发送的事件通信不正确
我正在努力让SSE工作。我有一个简单的网页,有两个按钮。每个人都向服务器发送一个POST请求,向列表中添加一条消息 当eventsource正在侦听时,服务器每秒检查一次列表,并将所有可用消息发送到客户端,同时将它们标记为已读,这样就不会再次发送到该客户端 它有点工作,但做了各种奇怪的事情:Javascript 服务器与ASP.Net发送的事件通信不正确,javascript,c#,asp.net,server-sent-events,Javascript,C#,Asp.net,Server Sent Events,我正在努力让SSE工作。我有一个简单的网页,有两个按钮。每个人都向服务器发送一个POST请求,向列表中添加一条消息 当eventsource正在侦听时,服务器每秒检查一次列表,并将所有可用消息发送到客户端,同时将它们标记为已读,这样就不会再次发送到该客户端 它有点工作,但做了各种奇怪的事情: 有时,按钮POST请求会无故延迟,然后立即发送 有时EventSource会重新启动自身,向服务器发出GET请求 有时,服务器在垃圾邮件发送按钮后调用Response.Flush()时会生成异常:“远程主
- 有时,按钮POST请求会无故延迟,然后立即发送
- 有时EventSource会重新启动自身,向服务器发出GET请求
- 有时,服务器在垃圾邮件发送按钮后调用Response.Flush()时会生成异常:“远程主机关闭了连接。错误代码为0x800704CD”
- 在按下按钮几次后,当我尝试重新加载页面时,它将永远保持“加载”
- getNotificationSystem()以线程安全的方式获取用户可用的所有消息
- AddNotification()添加消息
public void GetNotifs() {
try {
Response.ContentType = "text/event-stream";
while(true) {
List<string> Notifs = NotificationSystem.GetNotifications( GetUserId() );
if(Notifs != null && Notifs.Count > 0) {
foreach(var Text in Notifs) {
Response.Write( string.Format( "data: {0}\n\n", Text ) );
}
Response.Flush();
}
Thread.Sleep( 1000 );
}
} catch(Exception ex) {
Response.Close();
}
}
public ActionResult AddButton1() {
NotificationSystem.AddNotification( GetUserId(), "BTN1 (" + GetUserId() + ")" );
return Json( "OK" );
}
public ActionResult AddButton2() {
NotificationSystem.AddNotification( GetUserId(), "BTN2 (" + GetUserId() + ")" );
return Json( "OK" );
}
public void GetNotifs(){
试一试{
Response.ContentType=“文本/事件流”;
while(true){
List Notifs=NotificationSystem.GetNotifications(GetUserId());
if(Notifs!=null&&Notifs.Count>0){
foreach(Notifs中的var文本){
Write(string.Format(“数据:{0}\n\n”,Text));
}
Response.Flush();
}
睡眠(1000);
}
}捕获(例外情况除外){
Response.Close();
}
}
公共行动结果AddButton1(){
AddNotification(GetUserId(),“BTN1”(+GetUserId()+));
返回Json(“OK”);
}
公共行动结果AddButton2(){
AddNotification(GetUserId(),“BTN2”(+GetUserId()+));
返回Json(“OK”);
}
和客户端JS代码:
var urlMessages = "/Notifs/GetNotifs";
var urlButton1 = "/Notifs/AddButton1";
var urlButton2 = "/Notifs/AddButton2";
function PushBtn1() {
$.post(urlButton1);
}
function PushBtn2() {
$.post(urlButton2);
}
var myEventSource;
$(document).ready(function () {
myEventSource = new EventSource(urlMessages);
myEventSource.onmessage = function (e) {
console.log(e.data);
$('#EventLog').append("<li>Received: " + e.data + "<li>");
}
});
var urlMessages=“/Notifs/GetNotifs”;
var urlButton1=“/Notifs/AddButton1”;
var urlButton2=“/Notifs/AddButton2”;
函数PushBtn1(){
$.post(urlButton1);
}
函数PushBtn2(){
$.post(urlButton2);
}
myEventSource变种;
$(文档).ready(函数(){
myEventSource=新事件源(urlMessages);
myEventSource.onmessage=函数(e){
控制台日志(如数据);
$('#EventLog')。追加(收到:“+e.data+” ”;
}
});
您是否知道信号机
…对我来说,这似乎是您想要实现的目标的正确工具:)哦,是的,谢谢您的建议。我在谷歌搜索结果上看到过,很可能会使用它,现在我只是好奇是什么导致我的网站无法正常工作。这应该是一件非常基本的事情。