i am struggeling a lot to implement Server Site Events to stream data back to a WebApplication build with HTML an JavaScript (via using EventSource).
What I am doing in my system is, that a client system (C# console appliation) is permanently sending data to /getNotification?action=addEventChange&message="some text" and after receiving that message I want to trigger an event which should send the data back to my browser application which has a registered EventSource at /getNotification?action=readEventChange.
The event handling is working fine, but I figured out, that the Respons object is not available in my callback function (CB()) where i call further sendIncommingEvent().
I got there an Exception like "response is not available in this contect".
How can I make the response object available also in my callback? I found a messy workaround to go into an infinite loop after registering the eventhandler (see else if where i do the while(true) loop.)
That is working sometimes good and sometimes it is crashing me the IIS?!
So please guys help me here to solve my issue.
Many thanks in advance.
Cheers Dieter
Below you find as an example a codesnipped out of my cs function from the webform.
namespace xxxx
{
public partial class getNotification : System.Web.UI.Page
{
private static event EventHandler myHandler;
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["action"] == "addEventChange")
{
string sMsg = Request.QueryString["message"];
commonAESStuff.addEventChange(sMsg);
fireEvent(EventArgs.Empty);
}
else if (Request.QueryString["action"] == "readEventChange")
{
myHandler += CB;
while (true)
{
System.Threading.Thread.Sleep(1000);
}
}
public void sendIncommingEvent(string s)
{
try
{
Response.ContentType = "text/event-stream";
Response.Write("data:" + s.ToString() + "\n\n");
Response.Flush();
}
catch (Exception ex)
{
}
}
private void CB(object sender, EventArgs e)
{
string s = commonAESStuff.getEventChanges();
sendIncommingEvent(s);
}
protected virtual void fireEvent(EventArgs e)
{
EventHandler handler = myHandler;
if (handler != null)
{
handler(this, e);
}
}
}
}