您好,登录后才能下订单哦!
这篇文章主要为大家展示了“Asp.Net Core中WebSocket绑定的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Asp.Net Core中WebSocket绑定的示例分析”这篇文章吧。
说明
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 name="app"></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中WebSocket绑定的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。