过完2018年最后一个长假,看了年初给自己的flag,默默的发现距离感还是很强的。。。。
先说正题,最近在项目中碰到了实时通讯的需求,翻看了很多资料,最终选取signalr。
附上链接https://www.asp.net/signalr
项目是基于Angular4的,后端采用的Abp框架,自带通知架构。(https://aspnetboilerplate.com/Pages/Documents/Notification-System)
先说怎么将signalr引入项目中。
1、npm i signalr
在angular-cli.json文件里引入:"../node_modules/signalr/jquery.signalR.js"
2、建立连接
var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy(‘contosoChatHub‘);
contosoChatHubProxy.on(‘addContosoChatMessageToPage‘, function(name, message) {
console.log(name + ‘ ‘ + message);
});
connection.start().done(function() {
// Wire up Send button to call NewContosoChatMessage on the server.
$(‘#newContosoChatMessage‘).click(function () {
contosoChatHubProxy.invoke(‘newContosoChatMessage‘, $(‘#displayname‘).val(), $(‘#message‘).val());
$(‘#message‘).val(‘‘).focus();
});
});
3、后端配合
后端主要在于跨域,微软的官方文档里也有写到如何解决(https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#how-to-establish-a-cross-domain-connection)
4、代码基本:using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;
namespace MyWebApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We‘re not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
}
}
基础部分很是简单通透
在消息处理这一块,ABP已经处理的很好了,只要调取相应的方法即可。区分一下消息的时效性(暂时的消息还是永久性的消息)。
原文地址:https://www.cnblogs.com/Vibge/p/9774652.html