这篇文章主要为大家展示了“asp.net core 2.0中webapi集成signalr的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“asp.net core 2.0中webapi集成signalr的示例分析”这篇文章吧。
这里做了一个在.net core webapi里面集成signalr,我们就可以通过调用webapi来实现服务器向客户端推送消息
第一步引用nuget:Mrcrosoft.AspNetCore.SignalR
第二步添加配置代码:
首先ConfigureServices里面添加如下代码:
public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); services.AddCors(options => { options.AddPolicy("SignalrCore", policy => policy.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod()); }); services.AddSingleton<IServiceProvider, ServiceProvider>(); }
然后Configure里面添加
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //跨域支持 app.UseCors("SignalrCore"); app.UseSignalR(routes => { routes.MapHub<SignalrHubs>("signalrHubs"); }); app.UseWebSockets(); app.UseMvc(); }
然后我们添加一个hubs
public class SignalrHubs:Hub { /// <summary> /// 创建signalr链接 /// </summary> /// <param name="parentId">pid(作为用户组)</param> /// <param name="shopId">sid</param> public Task InitUser(string parentId, string shopId) { Groups.AddAsync(Context.ConnectionId, parentId); SignalrGroups.UserGroups.Add(new SignalrGroups() { ConnectionId = Context.ConnectionId, GroupName = parentId, ShopId = shopId }); return Clients.All.InvokeAsync("NoticeOnline", "用户组数据更新完成,新增id为:" + Context.ConnectionId + " pid:" + parentId + " sid:" + shopId + ""); } public override Task OnDisconnectedAsync(Exception exception) { //掉线移除用户 var user = SignalrGroups.UserGroups.FirstOrDefault(c => c.ConnectionId == Context.ConnectionId); if (user != null) { SignalrGroups.UserGroups.Remove(user); Groups.RemoveAsync(Context.ConnectionId, user.GroupName); } return base.OnDisconnectedAsync(exception); } }
PS:我这里是根据本人业务需要来做的,大家可以修改成其他的(用户量大的时候内存占用肯定高,这里只做一个简单的例子)
以上基本的环境搭建就已经完成了
接下来控制器里面的代码
[Produces("application/json")] [Route("api/MRSoftPush")] public class MRSoftPushController : Controller { private IHubContext<SignalrHubs> hubContext; public MRSoftPushController(IServiceProvider service) { hubContext = service.GetService<IHubContext<SignalrHubs>>(); } [HttpGet] public string Get() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"); } /// <summary> /// 单个connectionid推送 /// </summary> /// <param name="groups"></param> /// <returns></returns> [HttpPost,Route("AnyOne")] public IActionResult AnyOne([FromBody]IEnumerable<SignalrGroups> groups) { if (groups != null && groups.Any()) { var ids = groups.Select(c=>c.ShopId); var list = SignalrGroups.UserGroups.Where(c=>ids.Contains(c.ShopId)); foreach (var item in list) hubContext.Clients.Client(item.ConnectionId).InvokeAsync("AnyOne", $"{item.ConnectionId}: {item.Content}"); } return Ok(); } /// <summary> /// 全部推送 /// </summary> /// <param name="message"></param> /// <returns></returns> [HttpGet,Route("EveryOne")] public IActionResult EveryOne(string message) { hubContext.Clients.All.InvokeAsync("EveryOne", $"{message}"); return Ok(); } /// <summary> /// 组推送 /// </summary> /// <param name="group"></param> /// <returns></returns> [HttpPost,Route("AnyGroups")] public IActionResult AnyGroups([FromBody]SignalrGroups group) { if (group != null) { hubContext.Clients.Group(group.GroupName).InvokeAsync("AnyGroups", $"{group.Content}"); } return Ok(); } /// <summary> /// 多参数接收方式 /// </summary> /// <param name="message"></param> /// <returns></returns> [HttpGet,Route("MoreParamsRequest")] public IActionResult MoreParamsRequest(string message) { hubContext.Clients.All.InvokeAsync("MoreParamsRequest", message, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")); return Ok(); } }
服务器端的代码到这里全部完成,接下来咱们看客户端的代码
我的客户端代码是在另外一个项目里面,和服务器端是分离的
<input type="text" id="ParentId" placeholder="ParentId" /> <br /> <input type="text" id="ShopId" placeholder="ShopId" /> <br /> <button id="fuckyou">用户上线</button> <br /> <br /> <br /> <ul id="message" ></ul> @section scripts { <script> $(function () { let hubUrl = 'http://192.168.0.149:8009/signalrHubs'; let httpConnection = new signalR.HttpConnection(hubUrl); let hubConnection = new signalR.HubConnection(httpConnection); $("#fuckyou").click(function () { hubConnection.invoke('InitUser', $("#ParentId").val(), $("#ShopId").val()); }); hubConnection.on('NoticeOnline', data => { $("#message").append("<li>" + data + "</li>"); }); hubConnection.on('EveryOne', data => { $("#message").append("<li style=\"color:red;\">全部推送:" + data + "</li>"); }); hubConnection.on('AnyGroups', data => { $("#message").append("<li style=\"color:black;\">单个用户组推送:" + data + "</li>"); }); hubConnection.on('AnyOne', data => { $("#message").append("<li style=\"color:blue;\">单个ID推送:" + data + "</li>"); }); hubConnection.on('MoreParamsRequest', (message, date) => { $("#message").append("<li style=\"color:green;\">多参数接收:" + message + " : " + data + "</li>"); }); hubConnection.start(); }); </script> }
页面上引用连个js
<script src="/js/signalr-client.min.js"></script>
<script src="/js/jquery.min.js"></script>
到这里基本就已经完成了,下面看一下运行效果
以上是“asp.net core 2.0中webapi集成signalr的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。