Detailed description of WebSocket binding methods in Asp. Net Core, corewebsocket
Description
Websocket is a product of html5 and is also supported by asp.net core. The use of WebScoket operations in Asp. Net Core is basically the same as that in Asp.net. The difference is that listening is bound.
By default, Asp. Net Core2.0 supports WebSocket. You do not need to install the Nuget package.
Accept WebSocket requests by using the WebSockets. AcceptWebSocketAsync method in HttpContext and return the WebScoket object.
I won't talk much about it below. Let's take a look at the detailed introduction.
I. Example 1,
1. web socket-bound route listening in configure of the Startup File Startup in the background
Public void Configure (IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp ){...... // bind the WebSocket app. map ("/wsone/Connect", (con) => {con. useWebSockets (); WSHanleTwo _ two = new WSHanleTwo (); con. use (_ two. connect );});}
2. Define the request processing class
Using System. net. webSockets; using System. threading; using System. threading. tasks; namespace Core_Razor_2 {public class WSHanleTwo {private WebSocket socket = null; // create a connection to public async Task Connect (HttpContext context, Func <Task> n) {try {// execute to receive WebSocket socket = await context. webSockets. acceptWebSocketAsync (); this. socket = socket; // execute the listener await EchoLoop ();} catch (Exception ex) {throw ex ;}} /// <summary> /// Response Processing /// </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 ("server content"); var outgoing = new ArraySegment <byte> (backInfo, 0, incoming. count); await this. socket. sendAsync (outgoing, WebSocketMessageType. text, true, CancellationToken. none );}}}}
3. Front-end Request Code
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;
2. For simple binding, it can be encapsulated in this way
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> /// route binding process /// </summary> /// <param name = "app"> </param> public static void Map (IApplicationBuilder app) {app. useWebSockets (); app. use (SocketHandler. acceptor );}}
Route binding:
[Csharp] view plain copy // bind websocket app. Map ("/ws", SocketHandler. Map );
Asp. Net Core upload control: http://xiazai.jb51.net/201712/yuanma/Uploader (jb51.net).rar
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.