Signalr introduction and Asp.net

Source: Internet
Author: User

Signalr is an Asp.net asynchronous library that provides a mechanism to broadcast messages to multiple clients. Signalr can be used for persistent connection between clients and servers, allowing us to easily develop real-time applications, such as chat room online booking systems, stock trading, and other real-time applications. This can significantly reduce the server load and ensure there are no unnecessary requests from repeated client requests. Signalr is a non-Microsoft open-source project.
It implements the long polling mode, as shown in the figure below:

The traditional Ajax applications differ in the following aspects:

1. The server will block requests until there is data transmission or timeout.
2. The client's JavaScript response processing function will send a request again after processing the information returned by the server and re-establish the connection.
3. when the client processes received data and re-establishes a connection, new data may arrive at the server. The information will be saved by the server until the client re-establishes the connection, the client will retrieve all the information on the current server at a time.


Next we will use a simple example, first install it through nuget:

Install-Package SignalR

On the server side, create a mychat class inherited from the signalr. Hubs. Hub class:

    public class MyChat : Hub
    {
        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        public void Send(string message)
        {
            // Call the addMessage method on all clients         
            Clients.addMessage(message);
        }
    }


Now let's look at the front-end page, reference the corresponding client JS script, create a connection, and bind events.

    <title>dev home</title>
<body>
    <script src="../Scripts/jquery-1.7.2.js"></script>
    <script src="../Scripts/jquery.signalR-0.5.2.js"></script>
    <script src="/signalr/hubs" type="text/javascript"></script>
    <div>
        <script type="text/javascript">
            var chat;
            $(function () {
                // Created proxy            
                chat = $.connection.myChat;
                // Assign a function to be called by the server        
                chat.addMessage = onAddMessage;
                // Register a function with the button click               
                $("#broadcast").click(onBroadcast);
                // Start the connection        
                $.connection.hub.start();
            });
            function onAddMessage(message) {
                // Add the message to the list         
                $('#messages').append('<li>' + message + '</li>');
            }
            function onBroadcast() {
                // Call the chat method on the server           
                chat.send($('#message').val());
            }       
        </script>
        <input type="text" id="message" />
        <input type="button" id="broadcast" value="send" />
        <ul id="messages">
        </ul>
    </div>
</body>


After running, we can see that the current information is broadcast to all clients every time we click the button. The result using Fiddler is that when we submit the request raw of the CC string:

POST http://localhost:17347/signalr/send?transport=longPolling&connectionId=8eaf7e6b-f0e9-414a-8e97-68ad7ff02e2b HTTP/1.1Accept: application/json, text/javascript, */*; q=0.01Content-Type: application/x-www-form-urlencoded; charset=UTF-8X-Requested-With: XMLHttpRequestReferer: http://localhost:17347/mytest/MyChat.htmlAccept-Language: zh-cnAccept-Encoding: gzip, deflateUser-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)Host: localhost:17347Content-Length: 131Connection: Keep-AlivePragma: no-cachedata=%7B%22hub%22%3A%22MyChat%22%2C%22method%22%3A%22Send%22%2C%22args%22%3A%5B%22cc%22%5D%2C%22state%22%3A%7B%7D%2C%22id%22%3A1%7D

 

Response raw:

 

HTTP/1.1 200 OKServer: ASP.NET Development Server/10.0.0.0Date: Thu, 19 Jul 2012 03:12:28 GMTX-AspNet-Version: 4.0.30319Cache-Control: privateContent-Type: application/jsonConnection: CloseContent-Length: 66{"State":{},"Result":null,"Id":"1","Error":null,"StackTrace":null}
 

Then, from Fiddler, we can see that the first 3rd sessions show that HTTP is always connected. The above text is the raw of the first 2nd sessions.


 

Based on long polling, the client sends a request to the server without replying until data is returned. The Web Client suspends the connection only when the server returns a valid response. This is exactly what we want today-potentially reducing the stress on Web servers.

Hope to help your web development.

Articles you may be interested in:

Cascading drop-down list using knockoutjs and Asp.net MVC

 


Author: Petter Liu

Source: http://www.cnblogs.com/wintersun/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

This article is also published in Petter Liu blog, my independent blog.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.