开发者

Is it possible to subscribe to c# event with JavaScript?

I'm working on a web application that needs to frequently poll the server database and check for any available data to the client.

Ideally, I would need to be able get a javascript function callback in the server, in order to be able to call the javascript function back when开发者_JAVA百科ever any new data is available on the database, instead of having to poll the server every 5 seconds.

Simplifying, I would need to be able to call a method in the server and pass a js function as a parameter for callback. I want to avoid the overhead of polling the server repeatedly.

Is there any way this could be possibly done with asp.net and ajax?


The alternative that you're speaking about is some form of COMET style interface, where the client makes a request and the server holds on to it until it has a response. WCF has the PollingDuplex binding type, but I'm not terribly certain how to go about implementing it in javascript.

Well, this appears to be a very relevant link. It says Silverlight all over it, but it's an specifically for an AJAX browser application: http://www.silverlightshow.net/news/AJAX-Client-for-HTTP-Polling-Duplex-WCF-Channel-in-Microsoft-Silverlight-3-.aspx

UPDATE: I don't understand why all the alternate answers amount to "omg do polling on your own!" We have modern frameworks and protocols specifically to reduce to the amount of manual code we write. The PollingDuplex functionality provided by WCF does exactly what you want, and the link I provided implements the client side of that system in pure javascript.

Not sure what more you could want.

UPDATE 2:

Sorry, original article link. We all recognize that polling is the only solution for HTTP folks. The primary difference that the author is looking for is simulated push vs constant polling. You can achieve simulated push by placing a long running polling request to the server. With the right server architecture in place, it'll hold onto that request until it has data. Then it'll respond. At that point, the client immediately re-requests. In this manner, you utilize the existing HTTP request-response cycle to simulate "pushing" to the client.

This is primarily accomplished by having the appropriate server architecture in place. That way your requests are put to sleep and woken up in the appropriate manner. This is a far better paradigm than a manual polling answer where you ask the server for updates every 5 seconds. Chatty applications where you want responses now and not 4.8s from now is what I'm talking about. Manual polling (making a request for new data every 5s) gives the appearance of being laggy and during periods where no data is updated, it causes unnecessary request/response cycles.

From the article:

sl3duplex.js is a reusable, stand-alone JavaScript library that implements the client side of the HTTP polling duplex protocol compatible with the PollingDuplexHttpBinding in System.ServiceModel.PollingDuplex.dll

From the .HTM file in the download:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AJAX client for HTTP polling duplex WCF channel in Microsoft Silverlight 3</title>

    <script src="sl3duplex.js"></script>

    <script src="pubsub.js"></script>

    <script language="javascript">
        var sl3duplex = org.janczuk.sl3duplex;
        var proxy = null;

        function addNotification(text) {
            var notifications = document.getElementById("notifications");
            notifications.value += text + "\n";
            notifications.scrollTop = notifications.scrollHeight;
        }

        function alignUIWithConnectionState(connected) {
            document.getElementById("topicName").disabled =
               document.getElementById("subscribeButton").disabled = connected ? "disabled" : null;
            document.getElementById("publishText").disabled = connected ? null : "disabled"            
        }

        function onSubscribe() {                        
            proxy = new sl3duplex.Sl3DuplexProxy({
                url: window.location.href.substring(0, window.location.href.lastIndexOf("/")) + "/PubSubService.svc",
                onMessageReceived: function(body) {
                    addNotification("SERVER NOTIFICATION: " + (new sl3duplex.NotificationMessage(body)).text);
                },
                onError: function(args) {
                    addNotification("ERROR: " + args.error.message);
                    alignUIWithConnectionState(false);
                }
            });

            alignUIWithConnectionState(true);

            var topic = document.getElementById("topicName").value;
            proxy.send({ message: new sl3duplex.SubscribeMessage(topic),
                         onSendSuccessful: function(args) {
                             addNotification("CLIENT ACTION: Subscribed to topic " + topic);
                         }
                       });
        }

        function onPublish(event) {
            if (event.keyCode == 13) {
                var publishText = document.getElementById("publishText");
                var content = publishText.value;
                publishText.value = "";
                var topic = document.getElementById("topicName").value;

                proxy.send({ message: new sl3duplex.PublishMessage(topic, content),
                             onSendSuccessful: function(args) {
                                 addNotification("CLIENT ACTION: Published to topic " + topic + ": " + content);
                             }
                           });                               
            }
        }
    </script>

</head>
<body bgcolor="Tomato">
    <table style="width: 640px; font-family: Arial, Helvetica, sans-serif; font-size: 11px;"
        cellspacing="2" align="center">
        <tr>
            <td colspan="2">
                Topic to subscribe and publish to:
            </td>
        </tr>
        <tr>
            <td style="width: 448px">
                <input id="topicName" type="text" value="Dante" style="width: 100%" />
            </td>
            <td style="width: 192px">
                <input id="subscribeButton" type="button" value="Subscribe" style="width: 100%" onclick="onSubscribe();" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;
            </td>
        </tr>
        <tr>
            <td colspan=2>
                Notifications:
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <textarea id="notifications" name="S1" rows="18" readonly="readonly" style="width: 100%;
                    background-color: ButtonFace"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;
            </td>
        </tr>
        <tr>
            <td colspan="2">
                Enter text to publish and press Enter:
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="publishText" type="text" style="width: 100%" disabled="disabled" onkeypress="onPublish(event);" />
            </td>
        </tr>
    </table>
</body>
</html>

There's no silverlight objects being created or libraries being referenced. I can dump the .JS files into here as well, to show that it is merely a "reusable, stand-alone JavaScript library that implements the client side of the HTTP polling duplex protocol" and didn't hinge on silverlight being installed.


Maybe Im missing something obvious, but why not just simply do a GET request from ajax ( you can do this with jQuery or any major javascript framework easily) and then on response you can do whatever you need to update your view

this is a quick mod of a copy and paste from here

Ext.Ajax.request({
    url : 'http://yourdomain.com/controller/Action' , 
    params : { action : 'getDate' },
    method: 'GET',
    success: function ( result, request ) { 
        Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText); 
//.. do more view related stuff here , if this was a grid your would probably reload the store
    },
    failure: function ( result, request) { 
        Ext.MessageBox.alert('Failed', result.responseText); 
    } 
});

Of course, you would need to use a timer to do this ajax request at fixed intervals.

Hope it helps


It's pretty hard to implement publish-subscribe pattern in distributed world due to firewalls, etc.

AFAIK Microsoft is implementing new WCF binding with smart pooling to be used in SIlverlight and javascript. But, again, it is polling.

For now the only way to go is polling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜