標籤:asp.net core websocket
Websocket是html5後的產物,對於asp.net core中也得到了支援,首先在NuGet中添加Microsoft.AspNetCore.WebSockets的引用(現在是1.0.1版本,2017年3月7日發布的)。
首先在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中介軟體,用戶端發送的資訊顯示在控制項台上,用戶端會定時收到服務端推送的時間 /// </summary> public class WebSocketNotifyMiddleware { /// <summary> /// 管道代理對象 /// </summary> private readonly RequestDelegate _next; /// <summary> /// /// </summary> /// <param name="next"></param> public WebSocketNotifyMiddleware(RequestDelegate next) { _next = next; } /// <summary> /// 中介軟體調用 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task Invoke(HttpContext context) { //判斷是否為websocket請求 if (context.WebSockets.IsWebSocketRequest) { //接收用戶端 var webSocket = context.WebSockets.AcceptWebSocketAsync().Result; //啟用一個線程處理接收用戶端資料 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> /// 接收用戶端資料方法,這裡可以根據自己的需求切換功能代碼 /// </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); } } }}
添加中介軟體擴充
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通知中介軟體擴充 /// </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中添加自己建立的中介軟體了,代碼如下:
//添加websocket中介軟體 app.UseWebSockets(); app.UseWebSocketNotify();
到此服務端建立完成,接下來看用戶端:
<div> 當前在資料:<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="發送" /></div>@section scripts{<script>var socket; var uri = "ws://localhost:5000/ws";//初始化串連function doConnect(open, accept, close, error) {console.log("doConnect")//建立websocket,並定義事件回調 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); };}//發送資訊function doSend(message) { console.log("doSend") socket.send(message);}//關閉socketfunction doClose() { console.log("doClose") socket.close();} //開啟串連回調 function open() { console.log("open") document.getElementById("message").innerText = "串連開啟"; } //接收資料回調 function accept(result) { console.log("accept") document.getElementById("output").innerText=result; } //關閉串連回調 function close() { console.log("close") document.getElementById("message").innerText="串連關閉"; }//錯誤回調 function error(result) { console.log("error") alert("錯誤:"+result); } //開始方法 function start() { console.log("start") doConnect(open, accept, close, error); } function send() { console.log("send") doSend(document.getElementById("sendtxt").value); } </script>}
這裡只是一個基本的例子,可以根據自己的業務來實現不同的功能。
本文出自 “桂素偉” 部落格,請務必保留此出處http://axzxs.blog.51cto.com/730810/1909795
Asp.net core中的websocket