SignalR使用demo


Set up the Project

This section shows how to use Visual Studio 2013 and SignalR version 2.0 to create an empty ASP.NET web application, add SignalR, and create the chat application.

Prerequisites:

  • Visual Studio 2013. If you do not have Visual Studio, see ASP.NET Downloads to get the free Visual Studio 2013 Express Development Tool.

The following steps use Visual Studio 2013 to create an ASP.NET Empty Web Application and add the SignalR library:

  1. In Visual Studio, create an ASP.NET Web Application.

  2. In the New ASP.NET Project window, leave Empty selected and click Create Project.

  3. In Solution Explorer, right-click the project, select Add | SignalR Hub Class (v2). Name the class ChatHub.cs and add it to the project. This step creates the ChatHub class and adds to the project a set of script files and assembly references that support SignalR.

    Note: You can also add SignalR to a project by opening the Tools | Library Package Manager | Package Manager Console and running a command:

    install-package Microsoft.AspNet.SignalR

    If you use the console to add SignalR, create the SignalR hub class as a separate step after you add SignalR.

    Note: If you are using Visual Studio 2012, the SignalR Hub Class (v2) template will not be available. You can add a plain Class called ChatHub instead.

  4. In Solution Explorer, expand the Scripts node. Script libraries for jQuery and SignalR are visible in the project.

  5. Replace the code in the new ChatHub class with the following code.

    using System;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    namespace SignalRChat
    {
        public class ChatHub : Hub
        {
            public void Send(string name, string message)
            {
                // Call the broadcastMessage method to update clients.
                Clients.All.broadcastMessage(name, message);
            }
        }
    }
  6. In Solution Explorer, right-click the project, then click Add | OWIN Startup Class. Name the new class Startup and click OK.

    Note: If you are using Visual Studio 2012, the OWIN Startup Class template will not be available. You can add a plain Class called Startup instead.

  7. Change the contents of the new Startup class to the following.

    using Microsoft.Owin;
    using Owin;
    [assembly: OwinStartup(typeof(SignalRChat.Startup))]
    namespace SignalRChat
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // Any connection or hub wire up and configuration should go here
                app.MapSignalR();
            }
        }
    }
  8. In Solution Explorer, right-click the project, then click Add | HTML Page. Name the new page index.html.

  9. In Solution Explorer, right-click the HTML page you just created and click Set as Start Page.

  10. Replace the default code in the HTML page with the following code.

    Note: A later version of the SignalR scripts may be installed by the package manager. Verify that the script references below correspond to the versions of the script files in the project (they will be different if you added SignalR using NuGet rather than adding a hub.)

    
    
    
        </span><span class="pln">SignalR Simple Chat</span><span class="tag">
         type="text/css">
            .container {
                background-color: #99CCFF;
                border: thick solid #808080;
                padding: 20px;
                margin: 20px;
            }
        
    
    
         class="container">
             type="text" id="message" />
             type="button" id="sendmessage" value="Send" />
             type="hidden" id="displayname" />
             id="discussion">
            
        
src="Scripts/jquery-1.6.4.min.js" > src="Scripts/jquery.signalR-2.0.2.min.js"> src="signalr/hubs"> type="text/javascript"> $(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatHub; // Create a function that the hub can call to broadcast messages. chat.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('
').text(name).html(); var encodedMsg = $('
').text(message).html(); // Add the message to the page. $('#discussion').append('
  • ' + encodedName + ':  ' + encodedMsg + '
  • '
    ); }; // Get the user name and store it to prepend to messages. $('#displayname').val(prompt('Enter your name:', '')); // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); });
  • Save All for the project.

  • Run the Sample

    1. Press F5 to run the project in debug mode. The HTML page loads in a browser instance and prompts for a user name.

    2. Enter a user name.

    3. Copy the URL from the address line of the browser and use it to open two more browser instances. In each browser instance, enter a unique user name.
    4. In each browser instance, add a comment and click Send. The comments should display in all browser instances.

      Note: This simple chat application does not maintain the discussion context on the server. The hub broadcasts comments to all current users. Users who join the chat later will see messages added from the time they join.

      The following screen shot shows the chat application running in three browser instances, all of which are updated when one instance sends a message:

    5. In Solution Explorer, inspect the Script Documents node for the running application. There is a script file named hubs that the SignalR library dynamically generates at runtime. This file manages the communication between jQuery script and server-side code.

    你可能感兴趣的:(文档)