Websocket是html5后的產(chǎn)物,對(duì)于asp.net core中也得到了支持,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(現(xiàn)在是1.0.1版本,2017年3月7日發(fā)布的)。
創(chuàng)新互聯(lián)公司2013年開創(chuàng)至今,先為鳳縣等服務(wù)建站,鳳縣等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為鳳縣企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
首先在Configure中添加中間件
//添加websocket中間件 app.UseWebSockets();
接下來就要定義自己處理websocket的中間件了,代碼如下:
using Microsoft.AspNetCore.Http; using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Asp.NetCore_WebPage.Middleware { /// <summary> /// websocket中間件,客戶端發(fā)送的信息顯示在控件臺(tái)上,客戶端會(huì)定時(shí)收到服務(wù)端推送的時(shí)間 /// </summary> public class WebSocketNotifyMiddleware { /// <summary> /// 管道代理對(duì)象 /// </summary> private readonly RequestDelegate _next; /// <summary> /// /// </summary> /// <param name="next"></param> public WebSocketNotifyMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// 中間件調(diào)用 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task Invoke(HttpContext context) { //判斷是否為websocket請(qǐng)求 if (context.WebSockets.IsWebSocketRequest) { //接收客戶端 var webSocket = context.WebSockets.AcceptWebSocketAsync().Result; //啟用一個(gè)線程處理接收客戶端數(shù)據(jù) new Thread(Accept).Start(webSocket); while (webSocket.State == WebSocketState.Open) { webSocket.SendAsync(new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes($"{DateTime.Now}")), System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None); Thread.Sleep(1000); } } return this._next(context); } /// <summary> /// 接收客戶端數(shù)據(jù)方法,這里可以根據(jù)自己的需求切換功能代碼 /// </summary> /// <param name="obj"></param> void Accept(object obj) { var webSocket = obj as WebSocket; while (true) { var acceptArr = new byte[1024]; var result = webSocket.ReceiveAsync(new ArraySegment<byte>(acceptArr), CancellationToken.None).Result; var acceptStr = System.Text.Encoding.UTF8.GetString(acceptArr).Trim(char.MinValue); Console.WriteLine("收到信息:" + acceptStr); } } } }
添加中間件擴(kuò)展
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Asp.NetCore_WebPage.Middleware { /// <summary> /// websocket通知中間件擴(kuò)展 /// </summary> public static class WebSocketNotifyMiddlewareExtensions { /// <summary> /// 使用websocket通知 /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IApplicationBuilder UseWebSocketNotify( this IApplicationBuilder builder) { return builder.UseMiddleware<WebSocketNotifyMiddleware>(); } } }
這樣,就可以在Startup.cs中的Configure中添加自己創(chuàng)建的中間件了,代碼如下:
//添加websocket中間件 app.UseWebSockets(); app.UseWebSocketNotify();
到此服務(wù)端創(chuàng)建完成,接下來看客戶端:
<div> 當(dāng)前在數(shù)據(jù):<div id="message"></div> <div id="output"></div> <input class="form-control" type="text" id="sendtxt" value="測試" /> <input type="button" onclick="start()" value="開始" /> <input type="button" onclick="send()" value="發(fā)送" /> </div> @section scripts{ <script> var socket; var uri = "ws://localhost:5000/ws"; //初始化連接 function doConnect(open, accept, close, error) { console.log("doConnect") //創(chuàng)建websocket,并定義事件回調(diào) socket = new WebSocket(uri); socket.onopen = function (e) { open();}; socket.onclose = function (e) { close(); }; socket.onmessage = function (e) { accept(e.data); }; socket.onerror = function (e) { error(e.data); }; } //發(fā)送信息 function doSend(message) { console.log("doSend") socket.send(message); } //關(guān)閉socket function doClose() { console.log("doClose") socket.close(); } //打開連接回調(diào) function open() { console.log("open") document.getElementById("message").innerText = "連接打開"; } //接收數(shù)據(jù)回調(diào) function accept(result) { console.log("accept") document.getElementById("output").innerText=result; } //關(guān)閉連接回調(diào) function close() { console.log("close") document.getElementById("message").innerText="連接關(guān)閉"; }//錯(cuò)誤回調(diào) function error(result) { console.log("error") alert("錯(cuò)誤:"+result); } //開始方法 function start() { console.log("start") doConnect(open, accept, close, error); } function send() { console.log("send") doSend(document.getElementById("sendtxt").value); } </script> }
這里只是一個(gè)基本的例子,可以根據(jù)自己的業(yè)務(wù)來實(shí)現(xiàn)不同的功能。
本文題目:Asp.netcore中的websocket
鏈接分享:http://www.chinadenli.net/article28/joejjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站導(dǎo)航、電子商務(wù)、營銷型網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計(jì)、外貿(mào)建站、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)