這篇文章主要為大家展示了“Asp.Net Core中WebSocket綁定的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“Asp.Net Core中WebSocket綁定的示例分析”這篇文章吧。
在成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、外貿(mào)營銷網(wǎng)站建設(shè)中從網(wǎng)站色彩、結(jié)構(gòu)布局、欄目設(shè)置、關(guān)鍵詞群組等細(xì)微處著手,突出企業(yè)的產(chǎn)品/服務(wù)/品牌,幫助企業(yè)鎖定精準(zhǔn)用戶,提高在線咨詢和轉(zhuǎn)化,使成都網(wǎng)站營銷成為有效果、有回報(bào)的無錫營銷推廣。創(chuàng)新互聯(lián)建站專業(yè)成都網(wǎng)站建設(shè)十余年了,客戶滿意度97.8%,歡迎成都創(chuàng)新互聯(lián)客戶聯(lián)系。說明
Websocket是html5后的產(chǎn)物,對(duì)于asp.net core中也得到了支持,Asp.Net Core中WebScoket的操作使用基本上和Asp.net中相同,不同的是,綁定監(jiān)聽。
Asp.Net Core2.0默認(rèn)已經(jīng)支持WebSocket,不需要另外安裝Nuget包。
通過對(duì)HttpContext中的WebSockets.AcceptWebSocketAsync方法,接受WebSocket請(qǐng)求;并返回WebScoket對(duì)象。
下面話不多說了,來一起看看詳細(xì)的介紹吧。
一、示例1,
1.后臺(tái)啟動(dòng)文件Startup的configure中綁定WebSocket的路由監(jiān)聽
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp) { ...... //綁定WebSocket app.Map("/wsone/Connect", (con) => { con.UseWebSockets(); WSHanleTwo _two = new WSHanleTwo(); con.Use(_two.Connect); }); }
2.定義請(qǐng)求處理類
using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Core_Razor_2 { public class WSHanleTwo { private WebSocket socket = null; //創(chuàng)建鏈接 public async Task Connect(HttpContext context, Funcn) { try { //執(zhí)行接收 WebSocket socket = await context.WebSockets.AcceptWebSocketAsync(); this.socket = socket; //執(zhí)行監(jiān)聽 await EchoLoop(); } catch (Exception ex) { throw ex; } } /// /// 響應(yīng)處理 /// ///async Task EchoLoop() { var buffer = new byte[1024]; var seg = new ArraySegment (buffer); while (this.socket.State == WebSocketState.Open) { var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None); byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服務(wù)端相應(yīng)內(nèi)容"); var outgoing = new ArraySegment (backInfo, 0, incoming.Count); await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None); } } } }
3.前臺(tái)請(qǐng)求代碼
var socket; //var uri = "ws://" + window.location.host + "/ws"; var uri = "ws://" + window.location.host + "@Url.Action("Connect")"; var output; var text = "test echo"; function write(s) { var p = document.createElement("p"); p.innerHTML = s; output.appendChild(p); } function doConnect() { socket = new WebSocket(uri); socket.onopen = function (e) { write("opened " + uri); doSend(); }; socket.onclose = function (e) { write("closed"); }; socket.onmessage = function (e) { write("Received: " + e.data); socket.close(); }; socket.onerror = function (e) { write("Error: " + e.data); }; } function doSend() { write("Sending: " + text); socket.send(text); } function onInit() { output = document.getElementById("output"); doConnect(); } window.onload = onInit;
二、為了簡單綁定,可以這樣封裝
public class SocketHandler { public const int BufferSize = 4096; WebSocket socket; SocketHandler(WebSocket socket) { this.socket = socket; } async Task EchoLoop() { var buffer = new byte[BufferSize]; var seg = new ArraySegment(buffer); while (this.socket.State == WebSocketState.Open) { var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None); var outgoing = new ArraySegment (buffer, 0, incoming.Count); await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None); } } static async Task Acceptor(HttpContext hc, Func n) { if (!hc.WebSockets.IsWebSocketRequest) return; var socket = await hc.WebSockets.AcceptWebSocketAsync(); var h = new SocketHandler(socket); await h.EchoLoop(); } /// /// 路由綁定處理 /// /// public static void Map(IApplicationBuilder app) { app.UseWebSockets(); app.Use(SocketHandler.Acceptor); } }
路由綁定:
[csharp] view plain copy //綁定websocket app.Map("/ws", SocketHandler.Map);
以上是“Asp.Net Core中WebSocket綁定的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!