SingalR通过控制台实现跨域,实现多台服务器信息共享通讯
程序员文章站
2022-05-06 09:29:07
...
SignalR 是什么?
SignalR 是一个面向 ASP.NET 开发人员的库,可简化将实时 web 功能添加到应用程序的过程。 实时 web 功能是让服务器代码将内容推送到连接的客户端立即可用,而不是让服务器等待客户端请求新数据的能力。
废话少说,项目开上
1.首先我们要建一个控制台应用程序
先建一个hub类
[HubName("msghub")]
public class msgHub : BaseHub
{
/// <summary>
/// 客户端连接进入
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
/// <param name="userid"></param>
public void Join(int type, string code)
{
var ticket = Context.Request.QueryString.Get("ticket");
// LogHelper.Info(rr);
try
{
LogHelper.Error(ticket);
if (type == 0)
{
var UserData = DESEncrypt.Decrypt(ticket, DESEncrypt.DecryptKey);
var userBehind = JsonConvert.DeserializeObject<AuthenticationUser>(UserData);
Online(userBehind.UserName, userBehind.UserId, type, code);
}
var model = GetCurrInfo();
if (model != null)
{
Clients.Client(model.ConnectionId).ClientJoin(JsonHelper.ToObject(true, "添加成功"));
}
}
catch (Exception ex)
{
LogHelper.Error(ex.ToStr());
Clients.All.SendMsgCallback(JsonHelper.ToObject(true, "ewwewewee"));
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sendOutType"></param>
/// <param name="givePerson"></param>
/// <param name="receiveType"></param>
/// <param name="receivePerson"></param>
/// <param name="newContent"></param>
/// <param name="mP3Type"></param>
public void SendMsg(int receiveType, int receivePerson, string newContent, string mP3Type)
{
var model = GetCurrInfo();
if (model != null)
{
var cc = GetDestInfo(receiveType, receivePerson).Count;
Clients.Client(model.ConnectionId).SendMsgCallback(JsonHelper.ToObject(true, "添加成功"));
if (cc > 0)
{
GetDestInfo(receiveType, receivePerson).ForEach(x =>
{
Clients.Client(model.ConnectionId).RecieveMsgFromA(new MsgRespone() { From = model, To = x, Conetent = newContent, Audio = mP3Type, StatusCode = StatusCode.Success.GetHashCode() });
});
}
}
}
}
2.引用Owin,建立一个Startup
public class Startup
{
public void Configuration(IAppBuilder app)
{
//app.UseErrorPage();
app.UseCors(CorsOptions.AllowAll);
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
//Hub Mode
app.MapSignalR("/lcc", new HubConfiguration());
app.Map("/signalr", map =>
{
var config = new HubConfiguration
{
// You can enable JSONP by uncommenting this line
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
EnableJSONP = true
};
//config.EnableCrossDomain = true;
// Turns cors support on allowing everything
// In real applications, the origins should be locked down
map.UseCors(CorsOptions.AllowAll)
.RunSignalR(config);
});
// Turn tracing on programmatically
GlobalHost.TraceManager.Switch.Level = SourceLevels.Information;
}
}
3.设置启动程序
class Program
{
public static ServiceCollection services { get; set; }
public static HostingEnvironment HostingEnvironment { get; set; }
public static void Main(string[] args)
{
SingarTest();
}
public static void SingarTest()
{
string url = "http://127.0.0.1:8085";
using (WebApp.Start<Startup>(url))
{
System.Console.WriteLine("Server running at "+ url);
System.Console.ReadLine();
}
}
}
这样一个控制台就这样建立起来了,编译运行这个控制台放到云服务器,
看看效果
4.web前端如何引用呢
服务端的hub刚部署到云服务器,比如云服务器用域名指向是:test.hub.com
<!--引用SignalR库. -->
<script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
<!--引用云服务器SignalR 集线器(Hub)脚本.在运行的时候在浏览器的Source下可看到 -->
<script src="http://test.hub.com/signalr/hubs"></script>
页面开始调用触发连接和发送消息,这里我封装了一下
$.connection.hub.url = "http://test.hub.com/signalr";
var hubobj= $.connection.testHub;
$(function () {
HubHandle.Init();
});
///定义一个消息对象
var HubHandle= {
Init: function () {
var data = "这里存放秘钥连接字符串";
// $.connection.hub.qs = { 'ticket': data };//hub如何传参
$.connection.hub.start().done(function () {
var ticket =data ;
hubobj.server.join(ticket , Math.ceil(Math.random() * 100000));
});
},
}
//服务器返回加入消息消息
hubobj.client.Join= function (message) {
console.log(message);
}
//服务器返回消息
hubobj.client.recieveMsg = function (message) {
console.log(message);
}
好了 ,到这里就大功告成了,亲测可用跨域可用 !