WebForm SignalR 实时消息推送

2015-09-11  本文已影响2183人  过桥

实现效果

WebFrom + SignalR 实时消息,聊天室,即时消息


代码示例

动态链接库

添加基础动态链接库

Microsoft.AspNet.SignalR.Core.dll
Microsoft.AspNet.SignalR.Owin.dll
Microsoft.AspNet.SignalR.SystemWeb.dll
Microsoft.Owin.Host.SystemWeb.dll
Owin.dll
Newtonsoft.Json.dll

Global.asax

应用程序文件添加MapHubs

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
       RouteTable.Routes.MapHubs();
    }
}

继承 Hub

编写集成类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

/// <summary>
/// PushHub 的摘要说明
/// </summary>
public class PushHub : Hub
{
    public PushHub()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
}

聊天室页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChatRoom.aspx.cs" Inherits="WebApp.CustomApp.Message.ChatRoom" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <script src="../../Plugins/jquery.signalR-1.1.4.js" type="text/javascript"></script>
    <script src="/Signalr/Hubs"></script>
    <script>
        function SendMsg() {
            var data = { name: $("#txtName").val(), msg: $("#txtMessage").val() };
            $.post("ChatRoom.aspx", data, function (msg) { });
        }

        var pushHub = $.connection.pushHub;

        pushHub.client.sendMessage = function (name, message, time) {
            var flag = time + " " + name + " 说:" + message + "\r\n";
            $("#txtChatLog").val($("#txtChatLog").val() + flag);
        }

        $.connection.hub.logging = true;
        $.connection.hub.start();
    </script>

</head>
<body>

    <form>
        <div class="container">
            <div class="row">
                <br />
                <div class="form-group">
                    <label for="txtName">用户名</label>
                    <input type="text" class="form-control" id="txtName" placeholder="用户名" />
                </div>
                <div class="form-group">
                    <label for="txtMessage">消息内容</label>
                    <input type="text" class="form-control" id="txtMessage" placeholder="消息内容" />
                </div>
                <button type="button" class="btn btn-default" onclick="SendMsg()">发送</button>
                <br />
                <div class="form-group">
                    <label for="txtMessage">聊天记录</label>
                    <textarea id="txtChatLog" class="form-control" cols="100" rows="10"></textarea>
                </div>

            </div>
        </div>
    </form>


</body>
</html>

聊天室后台

using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApp.CustomApp.Message
{
    public partial class ChatRoom : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Form["name"] != null)
                {
                    SendMsg(Request.Form["name"].ToString(), Request.Form["msg"].ToString());
                }
            }
        }

        private void SendMsg(string name,string msg)
        {
            IHubContext chat = GlobalHost.ConnectionManager.GetHubContext<PushHub>();
            chat.Clients.All.sendMessage(name, msg, DateTime.Now.ToString());
        }

    }
}

注意事项

未生成 /Signalr/Hubs 脚本文件

如果通过浏览器查看时无法浏览 /Signalr/Hubs,可能是 Global.asax 未初始化 RouteTable.Routes.MapHubs();

Global.asax 中 RouteTable.Routes 找不到 MapHubs()

方式一

导入 System.Web.Routing

<%@ Import Namespace="System.Web.Routing" %>

方式二

或在 App_Code 文件夹下新建 Global.aspx.cs 文件,同时将原始 Global.aspx 修改如下

<%@ Application Codebehind="App_Code\Global.asax.cs" Inherits="Global" Language="C#" %> 
上一篇下一篇

猜你喜欢

热点阅读