日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

在ASP.NET CORE 2.0使用SignalR技术

發(fā)布時(shí)間:2023/12/4 asp.net 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在ASP.NET CORE 2.0使用SignalR技术 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、前言

上次講SignalR還是在《在ASP.NET Core下使用SignalR技術(shù)》文章中提到,ASP.NET Core 1.x.x 版本發(fā)布中并沒(méi)有包含SignalR技術(shù)和開發(fā)計(jì)劃中。時(shí)間過(guò)得很快,MS已經(jīng)發(fā)布了.NET Core 2.0 Preview 2 預(yù)覽版,距離正式版已經(jīng)不遠(yuǎn)了,上文中也提到過(guò)在ASP.NET Core 2.0中的SignalR將做為重要的組件與MVC等框架一起發(fā)布。它的開發(fā)團(tuán)隊(duì)也兌現(xiàn)了承諾,使用TypeScript對(duì)它的javascript客戶端進(jìn)行重寫,服務(wù)端方面也會(huì)貼近ASP.NET Core的開發(fā)方式,比如會(huì)集成到ASP.NET Core依賴注入框架中。


二、環(huán)境搭建

要在ASP.NET Core 2.0中使用SignalR,要先引用Microsoft.AspNetCore.SignalR 、 Microsoft.AspNetCore.SignalR.Http 兩個(gè)Package包。

目前ASP.NET Core 2.0與SignalR還都是Preview版本,所以NUGET上也找不到SignalR的程序包,想添加引用我們就得去MyGet上去找找。既然要用MyGet的話,就要為項(xiàng)目添加NuGet源了。

1.添加NuGet源

在程序根目錄新建一個(gè)命為NuGet.Config的文件內(nèi)容如下:

<?xml version="1.0" encoding="utf-8"?><configuration><packageSources><clear/><add key="aspnetcidev" value="https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json"/><add key="api.nuget.org" value="https://api.nuget.org/v3/index.json"/></packageSources></configuration>

2.編輯項(xiàng)目文件csproj

添加上面提到的兩個(gè)包的引用:

? ?<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview3-26040" /><PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-preview3-26037" /><PackageReference Include="Microsoft.AspNetCore.SignalR.Http" Version="1.0.0-preview3-26037" />

我在這個(gè)示例里使用的是目前的最高,當(dāng)然版本號(hào)每天都有可能發(fā)生變化,最新版本的SignalR,是不兼容.NET Core SDK 2.0 Preview 1中默認(rèn)創(chuàng)建項(xiàng)目時(shí)Microsoft.AspNetCore.All這個(gè)包的版本的,這里也修改修改一下版本號(hào)為:Microsoft.AspNetCore.All 2.0.0-preview3-26040。

當(dāng)然也可以用dotnet cli 來(lái)添加包引用:

dotnet add package Microsoft.AspNetCore.SignalR --version 1.0.0-preview3-26037 --source https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.jsondotnet add package Microsoft.AspNetCore.SignalR.Http --version 1.0.0-preview3-26037 --source https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json

3.添加配置代碼

我們需要在Startup類中的 ConfigureServices方法中添加如下代碼:

public void ConfigureServices(IServiceCollection services){services.AddSignalR(); }

在Startup類中的Configure方法中添加如下代碼:

public void Configure(IApplicationBuilder app, IHostingEnvironment env){app.UseStaticFiles();app.UseSignalR(routes =>{routes.MapHub<Chat>("hubs");}); }

4.添加一個(gè)HUB類

public class Chat : Hub{ ?
?public override async Task OnConnectedAsync() ? ?{
?? ? ? ?await Clients.All.InvokeAsync("Send", $"{Context.ConnectionId} joined");} ?
???public override async Task OnDisconnectedAsync(Exception ex) ? ?{ ? ? ? ?await Clients.All.InvokeAsync("Send", $"{Context.ConnectionId} left");} ? ?
???
???public Task Send(string message) ? ?{ ? ?
???
???? ?return Clients.All.InvokeAsync("Send", $"{Context.ConnectionId}: {message}");}
??
?? ?public Task SendToGroup(string groupName, string message) ? ?{ ? ? ? ?return Clients.Group(groupName).InvokeAsync("Send", $"{Context.ConnectionId}@{groupName}: {message}");} ?
??
?? ?public async Task JoinGroup(string groupName) ? ?{ ?
?? ?? ? ?await Groups.AddAsync(Context.ConnectionId, groupName); ? ? ? ?await Clients.Group(groupName).InvokeAsync("Send", $"{Context.ConnectionId} joined {groupName}");} ?
?? ?public async Task LeaveGroup(string groupName) ? ?{ ?
?? ?? ? ?? ? ?await Groups.RemoveAsync(Context.ConnectionId, groupName); ? ? ? ?await Clients.Group(groupName).InvokeAsync("Send", $"{Context.ConnectionId} left {groupName}");} ?
?? ?? ? ?? ? ?
?? ?? ?public Task Echo(string message) ? ?{ ? ?
?? ?? ? ? ?return Clients.Client(Context.ConnectionId).InvokeAsync("Send", $"{Context.ConnectionId}: {message}");} }

5.客戶端支持

  在wwwroot目錄下創(chuàng)建一個(gè)名為chat.html的Html靜態(tài)文件,內(nèi)容如下:

<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title></head><body><h1 id="head1"></h1><div><select id="formatType"><option value="json">json</option><option value="line">line</option></select><input type="button" id="connect" value="Connect" /><input type="button" id="disconnect" value="Disconnect" /></div><h4>To Everybody</h4><form class="form-inline"><div class="input-append"><input type="text" id="message-text" placeholder="Type a message, name or group" /><input type="button" id="broadcast" class="btn" value="Broadcast" /><input type="button" id="broadcast-exceptme" class="btn" value="Broadcast (All Except Me)" /><input type="button" id="join" class="btn" value="Enter Name" /><input type="button" id="join-group" class="btn" value="Join Group" /><input type="button" id="leave-group" class="btn" value="Leave Group" /></div></form><h4>To Me</h4><form class="form-inline"><div class="input-append"><input type="text" id="me-message-text" placeholder="Type a message" /><input type="button" id="send" class="btn" value="Send to me" /></div></form><h4>Private Message</h4><form class="form-inline"><div class="input-prepend input-append"><input type="text" name="private-message" id="private-message-text" placeholder="Type a message" /><input type="text" name="user" id="target" placeholder="Type a user or group name" /><input type="button" id="privatemsg" class="btn" value="Send to user" /><input type="button" id="groupmsg" class="btn" value="Send to group" /></div></form><ul id="message-list"></ul></body></html><script src="signalr-client.js"></script><script src="utils.js"></script><script>var isConnected = false;function invoke(connection, method, ...args) { ? ?if (!isConnected) { ? ? ? ?return; ? ?} ? ?var argsArray = Array.prototype.slice.call(arguments); ? ?connection.invoke.apply(connection, argsArray.slice(1)) ? ? ? ? ? ?.then(result => { ? ? ? ? ? ? ? ?console.log("invocation completed successfully: " + (result === null ? '(null)' : result)); ? ? ? ? ? ? ? ?if (result) { ? ? ? ? ? ? ? ? ? ?addLine('message-list', result); ? ? ? ? ? ? ? ?} ? ? ? ? ? ?}) ? ? ? ? ? ?.catch(err => { ? ? ? ? ? ? ? ?addLine('message-list', err, 'red'); ? ? ? ? ? ?});}

function getText(id) { ? ?return document.getElementById(id).value;}let transportType = signalR.TransportType[getParameterByName('transport')] || signalR.TransportType.WebSockets;document.getElementById('head1').innerHTML = signalR.TransportType[transportType];let connectButton = document.getElementById('connect');let disconnectButton = document.getElementById('disconnect');disconnectButton.disabled = true;var connection;click('connect', event => { ? ?connectButton.disabled = true; ? ?disconnectButton.disabled = false; ? ?let http = new signalR.HttpConnection(`http://${document.location.host}/hubs`, { transport: transportType }); ? ?connection = new signalR.HubConnection(http); ? ?connection.on('Send', msg => { ? ? ? ?addLine('message-list', msg); ? ?}); ? ?connection.onClosed = e => { ? ? ? ?if (e) { ? ? ? ? ? ?addLine('message-list', 'Connection closed with error: ' + e, 'red'); ? ? ? ?} ? ? ? ?else { ? ? ? ? ? ?addLine('message-list', 'Disconnected', 'green'); ? ? ? ?} ? ?} ? ?connection.start() ? ? ? ?.then(() => { ? ? ? ? ? ?isConnected = true; ? ? ? ? ? ?addLine('message-list', 'Connected successfully', 'green'); ? ? ? ?}) ? ? ? ?.catch(err => { ? ? ? ? ? ?addLine('message-list', err, 'red'); ? ? ? ?});});click('disconnect', event => { ? ?connectButton.disabled = false; ? ?disconnectButton.disabled = true; ? ?connection.stop() ? ? ? ?.then(() => { ? ? ? ? ? ?isConnected = false; ? ? ? ?});});click('broadcast', event => { ? ?let data = getText('message-text'); ? ?invoke(connection, 'Send', data);});click('join-group', event => { ? ?let groupName = getText('message-text'); ? ?invoke(connection, 'JoinGroup', groupName);});click('leave-group', event => { ? ?let groupName = getText('message-text'); ? ?invoke(connection, 'LeaveGroup', groupName);});click('groupmsg', event => { ? ?let groupName = getText('target'); ? ?let message = getText('private-message-text'); ? ?invoke(connection, 'SendToGroup', groupName, message);});click('send', event => { ? ?let data = getText('me-message-text'); ? ?invoke(connection, 'Echo', data);});</script>

值得注意的是,你可能會(huì)發(fā)現(xiàn),目前找不到signalr-client.js這個(gè)文件,它是怎么來(lái)的呢,有兩種方式:
第1種是通過(guò)下載SignalR的源代碼,找到Client-TS項(xiàng)目,對(duì)TypeScript進(jìn)行編譯可以得到。

第2種比較簡(jiǎn)單通過(guò)Npm可以在線獲取:

npm install signalr-client --registry https://dotnet.myget.org/f/aspnetcore-ci-dev/npm/


三、最后

  附上一個(gè)可用的Demo:https://github.com/maxzhang1985/AspNetCore.SignalRDemo

  GitHub:https://github.com/maxzhang1985/YOYOFx?如果覺(jué)還可以請(qǐng)Star下, 歡迎一起交流。

  .NET Core 開源學(xué)習(xí)群:214741894

相關(guān)文章:

  • ASP.NET SignalR 高可用設(shè)計(jì)

  • ASP.NET SignalR 2.0入門指南

  • SignalR SelfHost實(shí)時(shí)消息,集成到web中,實(shí)現(xiàn)服務(wù)器消息推送

  • ASP.NET WebHooks Receivers 介紹-WebHooks 讓其變得便捷

  • Signalr系列之虛擬目錄詳解與應(yīng)用中的CDN加速實(shí)戰(zhàn)

  • 采用HTML5+SignalR2.0(.Net)實(shí)現(xiàn)原生Web視頻

  • 基于.NET SingalR,LayIM2.0實(shí)現(xiàn)的web聊天室

原文地址:http://www.cnblogs.com/maxzhang1985/p/7118426.html


.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺(tái)或掃描二維碼關(guān)注

總結(jié)

以上是生活随笔為你收集整理的在ASP.NET CORE 2.0使用SignalR技术的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。