首页 > 代码库 > 聊天demo SignalR

聊天demo SignalR

1首先这个demo是针对 net版本是4.5的  SignalR   获取的是2.2的

2新建一个mvc项目  

 

3  Nuget  搜索 SignalR   安装如图的一项

技术分享

4新建一个 集线器类

技术分享

修改新建的 类 

     [HubName("demo")]    public class ChatHub:Hub    {        public void Send(string name, string message)        {            // Call the addNewMessageToPage method to update clients.            Clients.All.addNewMessageToPage(name, message);        }    }

5 Startup修改

public void Configuration(IAppBuilder app)        {            //ConfigureAuth(app);            app.MapSignalR();        }

6  在home/index中 

<div class="container">    <input type="text" id="message" />    <input type="button" tabindex="1" id="sendmessage" value="Send" />    <input type="hidden" id="displayname" />    <ul id="discussion"></ul></div>@section scripts {    <!--Script references. -->    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->    <!--Reference the SignalR library. -->    @*<script src="~/Scripts/jquery.signalR-1.0.1.js"></script>*@    <script src="~/Scripts/jquery-1.10.2.js"></script>    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>    <script src="~/signalr/hubs"></script>    <!--Reference the autogenerated SignalR hub script. -->    <!--SignalR script to update the chat page and send messages.-->    <script>        $(function () {            // Reference the auto-generated proxy for the hub.            var chat = $.connection.demo;            // Create a function that the hub can call back to display messages.            chat.client.addNewMessageToPage = function (name, message) {                // Add the message to the page.                $(#discussion).append(<li><strong> + htmlEncode(name)                    + </strong>:  + htmlEncode(message) + </li>);            };            // 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();                });            });        });        // This optional function html-encodes messages for display in the page.        function htmlEncode(value) {            var encodedValue = $(<div />).text(value).html();            return encodedValue;        }    </script>}

这个是官网的demo  就是展示界面 没什么好说的

另外附上 官网 下载zip  所有强大的功能都有!!

ASP.NET SignalR 官网 更强大的demo

 该项目demo  

下载

聊天demo SignalR