After hours of googling i found only one sample about event source using for asp.net (Not MVC). Firstly i must say i want to learn it and my final goal is to creating a friendly poker website. SignalR is very very good for my purpose but i do not want to use this because i heard:
SignalR is bad in performance
isn't it?(i hope not). My problem is when server sends response to client it sends the previous text not current:
$("#btnListen").click(function ()
{
var source = new EventSource('SSEHandler.ashx');
source.addEventListener("open", function (event)
{
$('#headerDiv').append('Latest 5 values');
}, false);
source.addEventListener("error", function (event)
{
if (event.eventPhase == EventSource.CLOSED)
{
$('#footerDiv').append('Connection Closed!');
}
}, false);
source.addEventListener("message", function (event)
{
console.log(event.data);
}, false);
});
And this is SSEHandler:
public class SSEHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
HttpResponse Response;
Response = context.Response;
Response.ContentType = "text/event-stream";
Response.Write(string.Format("data: {0}\n\n", "first"));
Response.Flush(); //client has no response received yet
Response.Write(string.Format("data: {0}\n\n", "second"));
Response.Flush(); //now client get "first".
Response.Close();
}
}
After executing this cods client console only have "first". And if i add this to end of SSEHandler:
Response.Write(string.Format("data: {0}\n\n", "third"));
Response.Flush();
In client console we have "first", "Second". Thanks for reading my long post.
Its been a while since you asked the question, but after struggling with this for a while myself I found a workaround I thought could be useful to share for others having the same issue.
Simply adding a comment (line that starts with colon) after each event will make the events appear when they should.
Note: The problem is more apparent when working with events that comes dynamically, since at that point the first event wont produce anything on the client, then when the second event hits, the first is displayed in the client. And this goes on with second and third etc..