Websocket是html5后的产物,对于asp.net core中也得到了支持,Asp.Net Core中WebScoket的操作使用基本上和Asp.net中相同,不同的是,绑定监听。
Asp.Net Core2.0默认已经支持WebSocket,不需要另外安装Nuget包。
通过对HttpContext中的WebSockets.AcceptWebSocketAsync方法,接受WebSocket请求;并返回WebScoket对象。
下面话不多说了,来一起看看详细的介绍吧。
一、示例1,
1.后台启动文件Startup的configure中绑定WebSocket的路由监听
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.定义请求处理类
using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Core_Razor_2 { public class WSHanleTwo { private WebSocket socket = null; //创建链接 public async Task Connect(HttpContext context, Func<Task> n) { try { //执行接收 WebSocket socket = await context.WebSockets.AcceptWebSocketAsync(); this.socket = socket; //执行监听 await EchoLoop(); } catch (Exception ex) { throw ex; } } /// <summary> /// 响应处理 /// </summary> /// <returns></returns> async Task EchoLoop() { var buffer = new byte[1024]; var seg = new ArraySegment<byte>(buffer); while (this.socket.State == WebSocketState.Open) { var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None); byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容"); var outgoing = new ArraySegment<byte>(backInfo, 0, incoming.Count); await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None); } } } }
3.前台请求代码
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<byte>(buffer); while (this.socket.State == WebSocketState.Open) { var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None); var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count); await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None); } } static async Task Acceptor(HttpContext hc, Func<Task> n) { if (!hc.WebSockets.IsWebSocketRequest) return; var socket = await hc.WebSockets.AcceptWebSocketAsync(); var h = new SocketHandler(socket); await h.EchoLoop(); } /// <summary> /// 路由绑定处理 /// </summary> /// <param></param> 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上传控件:(jb51.net).rar
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章: