Asp.Net Core中WebSocket绑定的方法详解
说明
Websocket是html5后的产物,对于asp.netcore中也得到了支持,Asp.NetCore中WebScoket的操作使用基本上和Asp.net中相同,不同的是,绑定监听。
Asp.NetCore2.0默认已经支持WebSocket,不需要另外安装Nuget包。
通过对HttpContext中的WebSockets.AcceptWebSocketAsync方法,接受WebSocket请求;并返回WebScoket对象。
下面话不多说了,来一起看看详细的介绍吧。
一、示例1,
1.后台启动文件Startup的configure中绑定WebSocket的路由监听
publicvoidConfigure(IApplicationBuilderapp,IHostingEnvironmentenv,IServiceProvidersvp) { ...... //绑定WebSocket app.Map("/wsone/Connect",(con)=> { con.UseWebSockets(); WSHanleTwo_two=newWSHanleTwo(); con.Use(_two.Connect); }); }
2.定义请求处理类
usingSystem.Net.WebSockets; usingSystem.Threading; usingSystem.Threading.Tasks; namespaceCore_Razor_2 { publicclassWSHanleTwo { privateWebSocketsocket=null; //创建链接 publicasyncTaskConnect(HttpContextcontext,Funcn) { try { //执行接收 WebSocketsocket=awaitcontext.WebSockets.AcceptWebSocketAsync(); this.socket=socket; //执行监听 awaitEchoLoop(); } catch(Exceptionex) { throwex; } } /// ///响应处理 /// ///asyncTaskEchoLoop() { varbuffer=newbyte[1024]; varseg=newArraySegment (buffer); while(this.socket.State==WebSocketState.Open) { varincoming=awaitthis.socket.ReceiveAsync(seg,CancellationToken.None); byte[]backInfo=System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容"); varoutgoing=newArraySegment (backInfo,0,incoming.Count); awaitthis.socket.SendAsync(outgoing,WebSocketMessageType.Text,true,CancellationToken.None); } } } }
3.前台请求代码
varsocket; //varuri="ws://"+window.location.host+"/ws"; varuri="ws://"+window.location.host+"@Url.Action("Connect")"; varoutput; vartext="testecho"; functionwrite(s){ varp=document.createElement("p"); p.innerHTML=s; output.appendChild(p); } functiondoConnect(){ socket=newWebSocket(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);}; } functiondoSend(){ write("Sending:"+text); socket.send(text); } functiononInit(){ output=document.getElementById("output"); doConnect(); } window.onload=onInit;
二、为了简单绑定,可以这样封装
publicclassSocketHandler { publicconstintBufferSize=4096; WebSocketsocket; SocketHandler(WebSocketsocket) { this.socket=socket; } asyncTaskEchoLoop() { varbuffer=newbyte[BufferSize]; varseg=newArraySegment(buffer); while(this.socket.State==WebSocketState.Open) { varincoming=awaitthis.socket.ReceiveAsync(seg,CancellationToken.None); varoutgoing=newArraySegment (buffer,0,incoming.Count); awaitthis.socket.SendAsync(outgoing,WebSocketMessageType.Text,true,CancellationToken.None); } } staticasyncTaskAcceptor(HttpContexthc,Func n) { if(!hc.WebSockets.IsWebSocketRequest) return; varsocket=awaithc.WebSockets.AcceptWebSocketAsync(); varh=newSocketHandler(socket); awaith.EchoLoop(); } /// ///路由绑定处理 /// ///publicstaticvoidMap(IApplicationBuilderapp) { app.UseWebSockets(); app.Use(SocketHandler.Acceptor); } }
路由绑定:
[csharp]viewplaincopy //绑定websocket app.Map("/ws",SocketHandler.Map);
Asp.NetCore上传控件:http://xiazai.jb51.net/201712/yuanma/Uploader(jb51.net).rar
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。