Detailed Explanation of WebSocket Binding Method in Asp. Net Core
- 2021-10-15 10:24:26
- OfStack
Description
Websocket is a product after html5, and is also supported in asp. net and core. The operation and use of WebScoket in Asp. Net and Core are basically the same as those in Asp. net, except that binding monitoring.
Asp. Net Core 2.0 already supports WebSocket by default, and no additional Nuget package is required.
Accepting the WebSocket request through the WebSockets. AcceptWebSocketAsync method in HttpContext; And returns an WebScoket object.
The following words are not much to say, let's take a look at the detailed introduction.
1. Example 1,
1. Route listening of WebSocket bound in configure of background startup file Startup
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider svp)
{
......
// Binding WebSocket
app.Map("/wsone/Connect", (con) =>
{
con.UseWebSockets();
WSHanleTwo _two = new WSHanleTwo();
con.Use(_two.Connect);
});
}
2. Define request processing classes
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace Core_Razor_2
{
public class WSHanleTwo
{
private WebSocket socket = null;
// Create a link
public async Task Connect(HttpContext context, Func<Task> n)
{
try
{
// Perform reception
WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
this.socket = socket;
// Execute monitoring
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(" Corresponding content of server ");
var outgoing = new ArraySegment<byte>(backInfo, 0, incoming.Count);
await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
3. Foreground 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, you can encapsulate
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>
/// Routing binding processing
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app)
{
app.UseWebSockets();
app.Use(SocketHandler.Acceptor);
}
}
Routing binding:
[csharp] view plain copy
// Binding websocket
app.Map("/ws", SocketHandler.Map);
Asp. Net Core Upload Control: http://xiazai. ofstack. com/201712/yuanma/Uploader (ofstack.com). rar
Summarize