Asp.NetCore中WebSocket绑定的示例分析-创新互联
这篇文章主要为大家展示了“Asp.Net Core中WebSocket绑定的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Asp.Net Core中WebSocket绑定的示例分析”这篇文章吧。
在成都网站设计、网站制作、外贸营销网站建设中从网站色彩、结构布局、栏目设置、关键词群组等细微处着手,突出企业的产品/服务/品牌,帮助企业锁定精准用户,提高在线咨询和转化,使成都网站营销成为有效果、有回报的无锡营销推广。创新互联建站专业成都网站建设十余年了,客户满意度97.8%,欢迎成都创新互联客户联系。说明
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, Funcn) { try { //执行接收 WebSocket socket = await context.WebSockets.AcceptWebSocketAsync(); this.socket = socket; //执行监听 await EchoLoop(); } catch (Exception ex) { throw ex; } } /// /// 响应处理 /// ///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("服务端相应内容"); var outgoing = new ArraySegment (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(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绑定的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
网站名称:Asp.NetCore中WebSocket绑定的示例分析-创新互联
网页地址:http://hbruida.cn/article/djshcg.html