使用SignalR构建一个最基本的web聊天室_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 使用SignalR构建一个最基本的web聊天室

使用SignalR构建一个最基本的web聊天室

 2013/7/18 18:00:48  Agile.Zhou(kklldog)  博客园  我要评论(0)
  • 摘要:WhatisSignalRASP.NETSignalRisanewlibraryforASP.NETdevelopersthatsimplifiestheprocessofaddingreal-timewebfunctionalitytoyourapplications.Real-timewebfunctionalityistheabilitytohaveserver
  • 标签:Web 使用 一个

What is SignalR

ASP.NET SignalR is a new library for ASP.NET developers that simplifies the process of adding real-time web functionality to your applications. Real-time web functionality is the ability to have server-side code push content to connected clients instantly as it becomes available.

You may have heard of the HTML5 WebSocket API that enables efficient bidirectional communication between the browser and server. SignalR uses Websockets when it is supported by the browser and the server, and gracefully falls back to other techniques and technologies when it is not. Either way, your application code stays the same.

SignalR provides a simple ASP.NET API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

上面是http://www.asp.net/signalr 的介绍。

本人英文不太好,简单翻译一下就是:SignalR是一个新的类库,它为ASP.NET开发者提供一个更简单的途径实现实时在线功能。SignalR可以实现服务端推送内容到客户端的功能。SignalR通过HTML5的WebSocket来实现服务端跟浏览器的通信。如果浏览器不支持WebSocket 那么就用其他的技术来实现。不管哪种技术,最后都是同样的效果。SignalR提供一组简单的ASP.NET API去构建RPC功能。它可以通过服务端代码去调用前端的javascript方法。SignalR同样为连接管理,群组连接,权限等提供了API。

/*以下不是翻译*/

SignalR非常微软,它被微软封装的非常易用。不管是后台类库,还是前端javascript都已经被你封装好了。SignalR依赖JQuery。SignalR的实现原理类似WCF,使用javascript代理类来调用服务端的方法。废话不多了上代码吧。

后台:

新建一个空的MVC项目,添加一个最基本的View跟Controller这个就不废话了。

在Global.asax的Start方法下面添加:

class="csharpcode">  RouteTable.Routes.MapHubs();

 

初始化hub。

在在解决方案下新建文件夹:Hub。添加一个类叫ChatHub:

  public class ChatHub : Microsoft.AspNet.SignalR.Hub
    {
        public void Send(string name, string message)
        {
            //send message to all pages
            Clients.All.SentMsgToPages(name, message);
        }
    }
啊,太简单了。只有一个方法一行代码。这个Send方法是提供给Client调用的。其中SentMsgToPages这是个动态方法,它表示前端的回调方法。也就是说Client调用Send方法把name跟message传回server,然后server会回调所有的连接的client的SentMsgToPages方法,把name跟message提供到client。

前台:

@{
    ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery.signalR-1.1.2.js"></script>
<script src="~/signalr/hubs"></script>

<script type="text/javascript">
    var chat = $.connection.chatHub;
    chat.client.SentMsgToPages = function (name, message) {
        // Add the message to the page. 
        $('#msgUl').append('<li><strong>' + name
            + '</strong>: ' + message + '</li>');
    };
    function sendMsg() {
        var userName = $("#userName").val();
        if (!userName) {
            $(".alert").show();
            return;
        }
        var msg = $('#messageBox').val();
        if (msg) {
            chat.server.send(userName, msg);
            $('#messageBox').val('').focus();
        }
           
    }
    $.connection.hub.start().done(
        function() {
            //设置按钮事件
            $("#btnSent").click(
                    sendMsg
            );
            $("#userName").focus(
                function () {
                    $(".alert").hide();
                }
            );
        }
        );
    $(document).ready(
        function () {
            //设置高度
            var msgListH = window.innerHeight - 150;
            $(".messageList").height(msgListH);
            $('#messageBox').keypress(
                function(e) {
                    var key = e.keyCode;
                    if (key == 13) {
                        sendMsg();
                    }
                }
                );
        }
    );
</script>
<h2>SignalR Chat Room</h2>
<div style="width: 99%;margin: 4px" id="outBoard" >
    <div  class="messageList" >
        <ul id="msgUl" class="unstyled">
            
        </ul>
    </div>
    <div class="form-inline">
        <input type="text" id="userName" placeholder="昵称" class="input-mini" />
        <input type="text" id="messageBox"  class="input-xxlarge"/>
        <input type="submit" value="发送" class="btn btn-info" id="btnSent" />
    
    </div>
      <div class="alert" style="display: none; width: 100px">
            必须输入昵称!
        </div>
</div>

前台除去HTML其实也很简单。最关键的也就3句话。
1 var chat = $.connection.chatHub;
客户端跟服务端建立连接。
2 chat.client.SentMsgToPages = function (name, message) { };
这就是服务端回调客户端的方法,给SentMsgToPages实现一个function表示如何处理返回值,这里当然是把message添加到聊天记录列表里。
3 chat.server.send(userName, msg); 
客户端通过chat对象调用服务端的send方法,把数据传回到服务器。

效果:

image

我们如此简单的就实现了一个最基本的聊天室,SignalR当然还可以做网页通知的推送,实时的进度条等等。这对ASP.NET程序员来说真是又一个神器。

发表评论
用户名: 匿名