Click here to Skip to main content
15,891,764 members
Articles / Web Development / HTML5
Tip/Trick

About HTML5 SSE, A Practical Working Example Application

Rate me:
Please Sign up or sign in to vote.
4.80/5 (3 votes)
6 Jan 2014CPOL2 min read 14.5K   393   6   1
HTML5 SSE example application
Sample Image - maximum width is 600 pixels

Introduction

SSE is still a relatively new technology that has been shipped with HTML5.

Sample Image - maximum width is 600 pixels

SSE stands for Server Sent Events.

This basically means that the client browser can get updated via an event that happens on the server.

The Opera web browser was actually the first browser to implement SSE.

Currently any browser that supports HTML5 will be able to use SSE.

Background

Previously, if you wanted to use a technology that gave browsers the ability to update, the best solution was to use XMPP. You are welcome to read more about xmpp here.

With the introduction of HTML5, you can now instead use SSE to do something similar.

To give a working example of SSE, I wrote a small application that gives a user the ability to chat on his website with another website visitor.

Using the Code

You can download the full application by clicking on the download link.

The application basically got a database where all the messages are stored. This is a webbased application in MVC5,

On the server, I have a method called GetChat that is checking the database all the time, to see if a new message has arrived.

On the client side, I have a JavaScript function that listens all the time to the server to see if a new event has been executed. Once the JavaScript sees that a new message has arrived from the server, it automatically displays the message and adds it to a div tag to display on the page.

This is my GetChat method:

C#
private static BlockingCollection<string> _chat = new BlockingCollection<string>();

        public ActionResult GetChat(string ChatId)
        {
            Models.ChatEntities db = new Models.ChatEntities();

            string sMessage;
            sMessage = "";

            string Result = "";
            try
            {
                var x = (from m in db.Chats
                         orderby m.DateCreated descending
                         select m).FirstOrDefault();
               
                    Result = x.Message;
                    sMessage = Result + "," + "0";

                    if (string.IsNullOrEmpty(Result))
                    {
                        sMessage = "0,0";
                    }
               
            }
            catch
            {
                sMessage = "0,0";
            }
            _chat.Add(sMessage);

            var result = string.Empty;
            var sb = new StringBuilder();
            if (_chat.TryTake(out result, TimeSpan.FromMilliseconds(1000)))
            {
                JavaScriptSerializer ser = new JavaScriptSerializer();
                var serializedObject = ser.Serialize(new { item = result, message = sMessage });
                sb.AppendFormat("data: {0}\n\n", serializedObject);
            }
            return Content(sb.ToString(), "text/event-stream");
        }

On the client side in your browser, I add the following JavaScript that calls the

GetChat
method:

C#
var source = new EventSource("GetChat?ChatId=@Html.Raw(ViewBag.ChatId)");

        //alert(source);
        source.addEventListener('message', function (e) {

            //alert('New Message!');
            var data = JSON.parse(e.data);

            var sStr;

            sStr = data.message;
            if (sStr != "0,0") {

                var arrC;

                arrC = sStr.split(",");

                var result;

                result = arrC[0];

                var LastM;

                LastM = document.getElementById("LastM").value;

                if (result != LastM) {

                    document.getElementById("result").innerHTML += result + "";
                    document.getElementById("LastM").value = result;
                }
            }
            else {
                document.getElementById("result").innerHTML = "Chat started." + "";
            }

        }, false);

Note the addEventListener that takes the data from the server and displays it in the page.

Points of Interest

SSE is a great technology and makes life easier with its not so complex way to implement. It also saves development time to use this great technology.

Sample Image - maximum width is 600 pixels

History

  • Version 1.0 of SSE HTML5 Chat application

You are welcome to use the source code in your own application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
South Africa South Africa
Gideon Louw is a qualified MCSD and software professional.

He developed several industrial and government related applications that has successfully been installed all over the world.

Comments and Discussions

 
QuestionHow 2 Pin
brighton katsuwa9-Jun-21 23:45
brighton katsuwa9-Jun-21 23:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.