SignalR 简单示例

原文:SignalR 简单示例

一、什么是 SignalR

  ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

 

二、简单示例

  新建项目 SignalRChat

  选择 Empty 模板

  安装 SignalR

  添加完查看 Scripts 文件夹

  添加 Signal Hub Class (V2)

  代码如下

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

namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            Clients.All.broadcastMessage(name, message);
        }
    }
}

  添加 OWIN Startup class

  代码如下

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

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

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

  添加 HTML 页面

  代码如下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>SignalR Simple Chat</title>
    <style type="text/css">
        .container {
            background-color: #99CCFF;
            border: thick solid #808080;
            padding: 20px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <input type="text" id="message" />
        <input type="button" id="sendmessage" value="Send" />
        <input type="hidden" id="displayname" />
        <ul id="discussion"></ul>
    </div>
    <!--Script references. -->
    <!--Reference the jQuery library. -->
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <!--Reference the SignalR library. -->
    <script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="signalr/hubs"></script>
    <!--Add script to update the page and send messages.-->
    <script type="text/javascript">
        $(function () {
            //To enable logging for your hub‘s events in a browser, add the following command to your client application
            $.connection.hub.logging = true;
            // 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 = $(‘<div />‘).text(name).html();
                var encodedMsg = $(‘<div />‘).text(message).html();
                // Add the message to the page.
                $(‘#discussion‘).append(‘<li><strong>‘ + encodedName + ‘</strong>:&nbsp;&nbsp;‘ + encodedMsg + ‘</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();
                });
            });
        });
    </script>
</body>
</html>

  F5 运行,复制 URL 再打开一个新浏览器窗口同时运行,分别输入 NameOneNameTwo

  如果是 IE 浏览器,打开 Soultion Explorer,可以看到 hubs 文件

  F12 打开控制台,发现使用的是 ForeverFrame (如果想在控制台查看日志,代码中必须包含 $.connection.hub.logging = true;)

  Chrome 效果如下

参考文章:http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr

代码下载

SignalRChat

时间: 2024-08-30 00:14:12

SignalR 简单示例的相关文章

AMQP消息队列之RabbitMQ简单示例

前面一篇文章讲了如何快速搭建一个ActiveMQ的示例程序,ActiveMQ是JMS的实现,那这篇文章就再看下另外一种消息队列AMQP的代表实现RabbitMQ的简单示例吧.在具体讲解之前,先通过一个图来概览下: 1.添加Maven依赖 <!-- rabbitmq begin --> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit

HMM的维特比算法简单示例

今天读了一位大牛的关于HMM的技术博客,读完之后,写了一个关于维特比算法的简单示例,用scala和java语言混合编写的.现在上传之. package com.txq.hmm import java.utilimport scala.collection._ /** * HMM维特比算法,根据显示状态链条估计隐式链条 * @param states 隐式states * @param observations 显式states * @param start_probability 初始概率向量

spring-servlet.xml简单示例

spring-servlet.xml简单示例 某个项目中的spring-servlet.xml 记下来以后研究用 1 <!-- springMVC简单配置 --> 2 <?xml version="1.0" encoding="UTF-8"?> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://w

关于Ajax实现的简单示例

一.代码示例 关于Ajax的基本概念(包括XMLHttpRequest对象及其相关方法属性)移步这里(w3school中文版)学习了解. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>使用Ajax异步加载数据</title> <script type = "text/javasc

【转】bind简单示例

bind简单示例代码 namespace { class placeholder_ {}; placeholder_ __1; } template <typename R, typename T, typename Arg> class simple_bind_t { private: typedef R (T::*F)(Arg); F f_; T* t_; Arg& a_; public: simple_bind_t(F f, T* t, Arg &a) : f_(f),

SQL左连接、右连接和内连接的简单示例

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录: right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录: inner join(等值连接) 只返回两个表中联结字段相等的行:举例如下: -------------------------------------------- 表A记录如下: aID aNum 1 a20050111 2 a20050112 3 a20050113 4 a20050114 5 a20050115 表B记录

Backbone简单示例

要的资源: <script type="text/javascript" src="../dep/underscore-1.6.0.min.js"></script> <script type="text/javascript" src="../dep/jquery-1.11.1.min.js"></script> <script type="text/javas

动态网站开发技术学习2:VS 2010制作作第一个简单示例网站

制作一个简单示例网站的步骤: 一,启动VS 2010开发环境,选择菜单中的"文件",选择其中的"新建",再选择"网站",会弹出"新建网站"对话框. 二,在"新建网站"的对话框,在"已安装模板"中选择Visual C#,右侧的选择"ASP.NET网站"选项,单击"新建网 站"中的"文件系统",下拉菜单中有"文件系统&qu

简单示例

下面是一个简单示例,当阀切换至自动模式时,会自动向储罐中补水,到达设定值后自动关闭.当储罐中水位到达设定值后水泵自动开启,水位低时联锁关闭. 上图分别显示了阀门和水泵操作面板 上图显示了水泵的联锁信息 上图是参数设置 上图显示了水位曲线