Signal's first simple demo

 

 

 

Simplest chat room feature

1. Create an MVC 4 (MVC 5 is also similar) project with VS 2013

 

1.1 Choose template as basic

2. Install SignalR with NuGet

 

3 After the installation is complete, let's add a folder called MyHub and add a SignalR hub (V2) to it, named MyChatHub

3.1 Let's customize our own method name Send for sending messages: (will be used to send messages in groups later)

4 Create a HomeController and use ViewBab to save a random number to identify the user name.

 

 5. Create a Home folder in the Views folder, and create a view Index in the Home directory

 

 6. First import the corresponding JQ 1.8 (or higher) version package, and then import SignalR,

 

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.3.min.js"></script>

<script src="@Url.Content("~/signalr/hubs")"></script>

<div>
    Your name: @ViewBag.clientName
</div>

<input type="text" id="txt_msg" />
<input type="button" onclick="SendMsg()" value="发送消息" />

<div>
    Received message:
    <div id="div_msg">

    </div>
</div>

< script > 
    var chat = $.connection.myChatHub; // Your hub name, the first letter must be lowercase 
    var myClientName =  " @ViewBag.ClientName " ;
    $(function () {
        
        chat.client.broadcastMessage =  function (name, message) { // The broadcast message received by the client, processing logic 
            $( " #div_msg " ).append( " <p><b> "  + name +  " </b > Say to everyone:   "  + message +  " </p> " );
        };


        $.connection.hub.start().done( function () { // Start the hub 
            console.log( " connect ok. " );
        });

    })


    function SendMsg() {
        chat.server.send(myClientName, $( " #txt_msg " ).val()).done( function () { // call the send message method in the hub 
            console.log( " send Msg success " ); // message Send successful processing logic 
        }).fail( function (e) {
            console.warn( " send msg error " ,e); // send failed 
        });
    }
</script>

7. Add a Startup file to the project

 

 code show as below:

[assembly: OwinStartup(typeof(TestSignalR2.Startup))]

namespace TestSignalR2
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure the application, visit http://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}

F5 to run it:

Open another window to send a message

 

OK, the test passed, the simplest group chat function.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324525437&siteId=291194637