提供的官方参考文档:
https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr
系统必备
带有 ASP.NET 和 Web 开发工作负荷的 Visual Studio 2017。
本部分演示如何使用 Visual Studio 2017 和 SignalR 2 创建一个空的 ASP.NET web 应用程序
在 “添加新项-SignalRChat” 中,选择 "安装 > Visual C# > Web > " SignalR ,然后选择 " SignalR Hub 类(v2) "。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace WebApplication1
{
public class MsgHub : Hub
{
//在hub中编写的方法,都要被客户端调用的方法
public void SendMsg(string name,string txt)
{
//服务器主动调用客户端的方法
Clients.All.getMsg(name,txt);
}
}
}
在解决方案资源管理器中,右键单击项目,然后选择 “添加 > 新项”。
在 “添加新项”-SignalRChat选择 "安装 > Visual C# > Web “,然后选择 " OWIN Startup 类”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
namespace WebApplication1
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
在解决方案资源管理器中,右键单击项目,然后选择 “添加 > " HTML 页”。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="Scripts/jquery-3.3.1.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
$(function() {
$("#btnLogin").click(function () {
login();
});
});
function login() {
if ($("#txtName").val().length > 3) {
sessionStorage.setItem("user", $("#txtName").val());
} else {
alert("登录失败!");
return ;
}
serverClient();
}
function serverClient() {
//1.注册服务器连接
var msgHub = $.connection.msgHub;
//2.给客户端注册方法
//接收到消息之后做什么????
msgHub.client.getMsg = function (name, txt) {
var txtTemplate = `
<div>
<span>{{name}}</span>
<span>{{content}}</span>
</div>`;
var html = $(txtTemplate.replace(`{{name}}`, name)
.replace(`{{content}}`, txt));
if (name == sessionStorage.getItem("user")) {
html.css({ "color": "red" });
}
//追加html代码
$("#msgList").prepend(html);
}
//启动连接并绑定处理事件
$.connection.hub.start().done(function () {
$("#sendBtn").removeAttr("disabled").click(function () {
msgHub.server.sendMsg(sessionStorage.getItem("user"), $("#txtMsg").val());
})
}).fail(function () {
})
}
</script>
</head>
<body>
<div id="msgList">
</div>
<input type="text" id="txtName"/><button id="btnLogin">登陆</button>
<input type="text" id="txtMsg"/><button id="sendBtn" disabled="disabled">发送消息</button>
</body>
</html>
效果: