Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core principle of .NET WebSocket?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

. NET WebSocket core principle is what, many novices are not very clear about this, in order to help you solve this problem, the following small series will be explained in detail for everyone, there are people who need this can learn, I hope you can gain something.

Let's dive into the basics first to understand what goes on behind the scenes with WebSockets.

WebSockets

WebSockets is introduced to support bidirectional communication between client and server.

HTTP 1.0: Every time we send a request to the server, we need to recreate the connection (close the previous connection).

HTTP 1.1: New keep-alive syntax introduces persistent connections, so connections can be reused--this reduces communication latency (because the server is aware of the client and does not need to reopen the handshake for each request)

WebSockets are attached to the HTTP 1.1 persistent connection mechanism, so if you are initiating a WebSockets connection for the first time, this is actually an HTTP 1.1 request, and full duplex communication begins after successful negotiation.

The following figure describes the initialization (handshake), data transfer, and closing of WebSockets.

The protocol has two parts: handshake and data transfer.

handshake

WebSocket has good compatibility with HTTP protocol. The "handshake" phase uses the HTTP protocol, and the default is port 80/443, so it is not easy to shield when shaking hands, and it can pass through various HTTP proxy servers.

The protocol identifier is ws(or wss if encrypted) and the server URL is the URL.

ws://example.com:80/some/path

In short, WebSocket connections are based on HTTP(transmitted over TCP) on a single port:

1. The server listens for incoming TCP socket connections on a specified port, such as 80/443

2. The client initiates the handshake with an HTTP GET request (this is where the "Web" in "WebSockets" comes from).

In the request header, the client will ask the server to upgrade the connection to WebSocket.

3. The server sends a handshake response informing the client that it will change the protocol from HTTP to WebSocket.

4. Client/server negotiates connection details. If the terms do not match, either party can withdraw.

GET /ws-endpoint HTTP/1.1 Host: example.com:80 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: L4kHN+1Bx7zKbxsDbqgzHw== Sec-WebSocket-Version: 13

Please note: Client sends Connection:Upgrade and Upgrade: websocket request headers Server handshake response:

HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: CTPN8jCb3BUjBjBtdjwSQCytuBo=

Note: The server returns HTTP/1.1 101 Switching Protocols status code, and other status codes other than 101 indicate handshake failure.

data transmission

Either party can send messages at any time because this is a full-duplex communication protocol.

Message consists of one or more frames, a frame can be binary, text, control frame (0x8 Close, 0x9 Ping,0xA Pong)

.NETCore Server listening WebSocketsdotnet new webapi -n WebSocketsTutorial dotnet add WebSocketsTutorial/ package Microsoft.AspNet.SignalR

To simplify this, I won't talk about SignalR(hubs and other things).

This will be entirely WebSocket based communication.

app.UseWebSockets();

Add WebSocketsController.cs and add the following code:

using System; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace WebSocketsTutorial.Controllers { [ApiController] [Route("[controller]")] public class WebSocketsController : ControllerBase { private readonly ILogger _logger; public WebSocketsController(ILogger logger) { _logger = logger; } [HttpGet("/ws")] public async Task Get() { if (HttpContext.WebSockets.IsWebSocketRequest) { using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); _logger.Log(LogLevel.Information, "WebSocket connection established"); await Echo(webSocket); } else { HttpContext.Response.StatusCode = 400; } } private async Task Echo(WebSocket webSocket) { var buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); _logger.Log(LogLevel.Information, "Message received from Client"); while (! result.CloseStatus.HasValue) { var serverMsg = Encoding.UTF8.GetBytes($"Server: Hello. You said: {Encoding.UTF8.GetString(buffer)}"); await webSocket.SendAsync(new ArraySegment(serverMsg, 0, serverMsg.Length), result.MessageType, result.EndOfMessage, CancellationToken.None); _logger.Log(LogLevel.Information, "Message sent to Client"); result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); _logger.Log(LogLevel.Information, "Message received from Client"); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); _logger.Log(LogLevel.Information, "WebSocket connection closed"); } } }

After the handshake, the server can push messages to the client without waiting for the client to initiate the message.

Start the ASP.NET Core server, the program listens for WebSockets connections at the/ws routing address, and sends back messages sent by the client.

Browser client using WebSockets api

Write js code in the browser Console to initiate client-side websockets requests:

let webSocket = new WebSocket('wss://localhost:5001/ws');

Two-way communication can be observed on the requested network- Messages tab:

In addition to this, the server/client maintains a pingpong mechanism to confirm whether the client is still alive.

If you really want to see these packages, use a tool like Wireshark.

There will only be one record of the whole process on Chrome-Network, so if you want to see "handshake process" please also check the tab page just in??.

Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report