一、准备工作
1、项目初始化(两个控制器-Login、index以及相应的视图)。
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/scripts/jquery-1.6.4.min.js"></script>
<!--引用SignalR库. -->
<script src="~/scripts/jquery.signalR-2.3.0.min.js"></script>
<!--引用自动生成的SignalR 集线器(Hub)脚本.在运行的时候在浏览器的Source下可看到
<script src="~/signalr/hubs"></script>这个js。这是在项目中找不到,是有signalr自己生成作为桥接的js。引入最重要的hubs js,这个js其实并不存在,SignalR会反射获取所有供客户端调用的方法放入hubs js中-->
<script src="~/signalr/hubs"></script>
</head>
<body>
<div>
@Html.DropDownList("hard-code-dropdownlist", new SelectList(ViewBag.hard_value, "Value", "Text"), new { @class = "btn btn-success dropdown-toggle form-control" })
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="messageBox"></ul>
</div>
<input type="button" id="clearcookie" value="清楚cookie" />
<input type="button" id="SendSystemMsg" value="发送系统消息" />
</div>
</body>
<script type="text/javascript">
$(function () {
//引用自动生成的集线器代理
var chat = $.connection.chatHub;
//定义服务器调用的客户端sendMessage来显示新消息
chat.client.sendMessage = function (name, message)
{
//向页面添加消息
$("#messageBox").append('<li><strong style="color:green">'+htmlEncode(name)+'</strong>:'+htmlEncode(message)+'</li>');
}
//设置焦点到输入框
$('#message').focus();
//开始连接服务器
$.connection.hub.start().done(function () {
// 连接成功时
$('#sendmessage').click(function () {
//调用服务器端集线器的Send方法
chat.server.sendMsg($('#message').val());
//清空输入框信息并获取焦点
$("#message").val('').focus();
})
}).fail(function (res) {
// 连接失败时
});
});
$("#clearcookie").click(function () {
$.ajax({
url: '/Index/ClearCookIe',
type:'post',
//dataType:'json',
timeout:1000,
success: function (data, status) {
if(data=="fail")
console.log(data)
else
location.href = data;
},
fail: function (err, status) {
console.log(err)
}
});
})
$("#SendSystemMsg").click(function () {
$.ajax({
url: '/Index/SendSystemMsg',
type: 'post',
//dataType:'json',
timeout: 1000,
success: function (data, status) {
console.log(data)
},
fail: function (err, status) {
console.log(err)
}
});
})
//为显示的消息进行html编码
function htmlEncode(value)
{
var encodeValue = $('<div/>').text(value).html();
return encodeValue;
}
</script>
</html>
知识兔public ActionResult ClearCookIe()
{
HttpCookie cookies = Request.Cookies["USERNAME"]; //一定要注意设置Cookies是用Response读取是用Request两者不一样!
if (cookies != null)
{
cookies.Expires = DateTime.Today.AddDays(-1);
Response.Cookies.Add(cookies);
Request.Cookies.Remove("USERNAME");
}
if (Request.Cookies["USERNAME"] == null)
{
return Content("/Login/Index");
}
else {
return Content("fail");
}
}
[HttpPost]
public ActionResult SendSystemMsg()
{
//从外部访问类访问服务器上相对应的hub服务方式
var hub = GlobalHost.ConnectionManager.GetHubContext<ServerHub>();
//在集线器外部推送消息
//hub.Clients.All.notice("都起来吃饭了");
hub.Clients.All.sendMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "都起来吃饭了");
if (1 == null)
{
return Content("ok");
}
else
{
return Content("fail");
}
}
/*
//从外部访问持久性连接服务 方式
var connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<TestConnection>();//管理相对应的持久性连接
connectionContext.Connection.Broadcast("该吃饭了");//向所有已连接的客户端发送信息
*/
知识兔2、SignalR的准备:NuGet包管理器搜索:工具——>库程序包管理器——>Microsoft.AspNet.SignalR 或者 工具——>库程序包管理器——>程序包管理器控制台 Install-Package Microsoft.AspNet.SignalR。
二、新建startup文件(在App_Start目录内),用来启动SignalR
1、选择常规-->选择OWIN Startup类-->修改名字: StartupSignalR.cs
2、StartupSignalR.cs内添加 永久链接类的配置;//启动SignalR --详情进入文件类查看
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(ChatSignalR.App_Start.Startup))]
namespace ChatSignalR.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
}
}
知识兔三、新建Hub类,MyHub(在新建HubSignalR目录内)。此类的作用是用来与客户端的连接。
1、选择SignalR-->选择SignalR永久连接类(v2)文件类型-->修改名字: ServerHub.cs
四、在Login控制器写客户端JQ调用MyHub的方法。
这里有区别 (在集线器内用 1、[HubName("chatHub")]2、类的名字开头字母小写 永久链接类 只能在Startup 声明定义使用的方法 )