Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8057551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T09:04:13+00:00 2026-06-05T09:04:13+00:00

I am trying to set up a lightweight HTML5 Server-Sent Event implementation on my

  • 0

I am trying to set up a lightweight HTML5 Server-Sent Event implementation on my MVC 4 Web, without using one of the libraries available to implement sockets and similars.
The lightweight approach I am trying is:

Client side:
EventSource (or jquery.eventsource for IE)

Server side:
long polling with AsynchController (sorry for dropping here the raw test code but just to give an idea)

public class HTML5testAsyncController : AsyncController
    {
        private static int curIdx = 0;
        private static BlockingCollection<string> _data = new BlockingCollection<string>();
        static HTML5testAsyncController()
        {
            addItems(10);
        }
 //adds some test messages
        static void addItems(int howMany)
        {
            _data.Add("started");
            for (int i = 0; i < howMany; i++)
            {
                _data.Add("HTML5 item" + (curIdx++).ToString());
            } _data.Add("ended");
        }

// here comes the async action, 'Simple'
        public void SimpleAsync()
        {
            AsyncManager.OutstandingOperations.Increment();

            Task.Factory.StartNew(() =>
            {
                var result = string.Empty; var sb = new StringBuilder();
                string serializedObject = null;
            //wait up to 40 secs that a message arrives
                if (_data.TryTake(out result, TimeSpan.FromMilliseconds(40000)))
                {
                    JavaScriptSerializer ser = new JavaScriptSerializer();
                    serializedObject = ser.Serialize(new { item = result, message = "MSG content" });
                    sb.AppendFormat("data: {0}\n\n", serializedObject);
                }
                AsyncManager.Parameters["serializedObject"] = serializedObject;
                AsyncManager.OutstandingOperations.Decrement();
            });
        }
  // callback which returns the results on the stream
        public ActionResult SimpleCompleted(string serializedObject)
        { ServerSentEventResult sar = new ServerSentEventResult(); 
            sar.Content = () => { return serializedObject; };
            return sar;

        }
  //pushes the data on the stream in a format conforming HTML5 SSE
        public class ServerSentEventResult : ActionResult
        {
            public ServerSentEventResult() { }
            public delegate string GetContent(); 
            public GetContent Content { get; set; }        
            public int Version { get; set; }
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException("context");
                } if (this.Content != null)
                {
                    HttpResponseBase response = context.HttpContext.Response;
                    // this is the content type required by chrome 6 for server sent events              
                    response.ContentType = "text/event-stream";

                    response.BufferOutput = false;                // this is important because chrome fails with a "failed to load resource" error if the server attempts to put the char set after the content type          
                    response.Charset = null;
                    string[] newStrings = context.HttpContext.Request.Headers.GetValues("Last-Event-ID");
                    if (newStrings == null || newStrings[0] != this.Version.ToString())
                    {
                        string value = this.Content();
                        response.Write(string.Format("data:{0}\n\n", value));
                        //response.Write(string.Format("id:{0}\n", this.Version));
                    }
                    else
                    {
                        response.Write("");
                    }
                }
            }
        }
    }

The problem is on the server side as there is still a big gap between the expected result and what’s actually going on.

Expected result:

  • EventSource opens a stream connection to the server,
  • the server keeps it open for a safe time (say, 2 minutes) so that I am protected from thread leaking from dead clients,
  • as new message events are received by the server (and enqueued to a thread safe collection such as BlockingCollection) they are pushed in the open stream to the client:

    • message 1 received at T+0ms, pushed to the client at T+x
    • message 2 received at T+200ms, pushed to the client at T+x+200ms

Actual behaviour:

  • EventSource opens a stream connection to the server,
  • the server keeps it open until a message event arrives (thanks to long polling)
  • once a message is received, MVC pushes the message and closes the connection.
  • EventSource has to reopen the connection and this happens after a couple of seconds.
    • message 1 received at T+0ms, pushed to the client at T+x
    • message 2 received at T+200ms, pushed to the client at T+x+3200ms

This is not OK as it defeats the purpose of using SSE as the clients start again reconnecting as in normal polling and message delivery gets delayed.

Now, the question:
is there a native way to keep the connection open after sending the first message and sending further messages on the same connection?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T09:04:15+00:00Added an answer on June 5, 2026 at 9:04 am

    Instead of relying on SimpleComplete to send the data, you want to send the data using Response.Flush. By doing an AsyncManager.OutstandingOperations.Decrement(), you’re telling the AsyncController that you’re finished processing the request and you’re ready to send the response and close the connection. Instead, you avoid calling OutStandingOperations.Decrement() until the connection is lost, etc. Whenever you want to push a message to the client, you directly call Response.Write and Response.Flush from some background thread. Also, AsyncControllers have a default timeout after which they automatically close the connection. To get around that, you’ll want to use the NoAsyncTimeoutAttribute for the relevant actions.

    As a side note, AsyncController’s interface doesn’t really allow a clean way of implementing a SSE stream; I would have personally implemented a HttpTaskAsyncHandler given that I was using Asp.NET MVC 4.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to set it so if a certain condition is met then one of
I am using mac lion and eclipse indigo. I am trying set it up
Trying to set up an extension method in .Net 3.0 using generics and I
Trying to set up one-way SSL with Weblogic 11g and running into an issue.
Trying to set up caching on our datasets - we're using clr stored procedures
I'm trying to set up a websocket server in node.js but having problems. I
I'm trying to set the author when adding an event to a Google Calendar
Trying to set window.location or using window.navigate() to make the browser go to about:crash
Im trying to set port forwarding using c#, but I keep getting this error
Im trying set the single table inheritance model type in a form. So i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.