Click here to Skip to main content
15,895,746 members
Articles / Web Development / HTML

Using IHttpAsyncHandler and XMLHttpRequest to “push” messages to the client

Rate me:
Please Sign up or sign in to vote.
4.75/5 (14 votes)
30 Sep 2009CPL4 min read 84.5K   2K   61  
How you can let a web browser be a "listener" for chat messages pushed from a web server.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SandBox.CometSample.Default"  %>

<%--
//
// This code is released under Common Public License Version 1.0 (CPL)
// Full license text is available at http://www.opensource.org/licenses/cpl1.0.php
//
// Author  : Karel Boek
// Date    : Sept 29, 2009
// Contact : karel.boek@raskenlund.com
//
--%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">
        function init() {
            var send = document.getElementById('btnSend');

            if (!send.addEventListener) {
                send.addEventListener = function(type, listener, useCapture) {
                    attachEvent('on' + type, function() { listener(event) });
                }
            }

            send.addEventListener('click', function() { send(); }, false);
            
            hook();
        }

        function hook() {
            var url     = 'MyAsyncHandler.ashx?sessionId=<%= Session.SessionID %>';
            var request = getRequestObject();

            request.onreadystatechange = function() {
                try {

                    if (request.readyState == 4) {
                        if (request.status == 200) {
                            document.getElementById('incoming').innerHTML += request.responseText + '<br />';

                            // immediately send a new request to tell the async handler that the client is 
                            // ready to receive new messages;
                            hook();
                        }
                        else {
                            document.getElementById('incoming').innerHTML += request.responseText + '<br />';
                        }
                    }
                }
                catch (e) {
                    document.getElementById('incoming').innerHTML = "Error: " + e.message;
                }
            };

            request.open('POST', url, true);
            request.send(null);
        }
 
        function send() {
            var message   = document.getElementById('message').value;
            var recipient = document.getElementById('<%= ddlSessions.ClientID %>').value;
            var request   = getRequestObject();
            var url       = 'MyMessageHandler.ashx?message=' + message + '&recipient=' + recipient;
            var params    = 'message=' + message + '&recipient=' + recipient;

            document.getElementById('incoming').innerHTML += '<span style="color: #f00;">You wrote: ' + message + '</span><br />';
            
            request.onreadystatechange = function() { 
                if (request.readyState == 4 && request.status != 200)
                    alert('Error ' + request.status + ' trying to send message');
            };

            request.open('POST', url, true);
            request.send(params);
        }

        function getRequestObject() {
            var req;

            if (window.XMLHttpRequest && !(window.ActiveXObject)) {
                try {
                    req = new XMLHttpRequest();
                }
                catch (e) {
                    req = false;
                }
            }
            else if (window.ActiveXObject) {
                try {
                    req = new ActiveXObject('Msxml2.XMLHTTP');
                }
                catch (e) {
                    try {
                        req = new ActiveXObject('Microsoft.XMLHTTP');
                    }
                    catch (e) {
                        req = false;
                    }
                }
            }

            return req;
        }
    </script>

</head>
<%----%>

<body onload="setTimeout('init();', 500);">
    <form id="form1" runat="server">
    <div>
        Self:      <asp:Literal ID="ltlSessionId" runat="server" /><br />
        Message:   <input type="text" id="message" /><br />
        Recipient: <asp:DropDownList ID="ddlSessions" runat="server" />
        <br />
        <input type="button" id="btnSend" value="Send Message!" onclick="send();" />
        <hr />
        <div id="incoming">
        </div>
    </div>
    </form>
</body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)


Written By
Software Developer Raskenlund
Norway Norway
Professional System Architect and Developer

Comments and Discussions