.net 8 使用 quic 協議通訊

debian環境安裝 quic支持

# 1. 添加unstable倉庫(如果您使用的是Debian的不穩定分支)
sudo apt install apt-transport-https ca-certificates
sudo wget -O /etc/apt/trusted.gpg.d/microsoft.gpg https://packages.microsoft.com/keys/microsoft.asc
echo "deb [arch=amd64] https://packages.microsoft.com/debian/$(lsb_release -cs) prod-unstable main" | \sudo tee /etc/apt/sources.list.d/msprod.list# 2. 更新包列表
sudo apt update# 3. 安裝libmsquic
sudo apt install libmsquic

window環境要求

要求Windows 11、Windows Server 2022 或更新版本

代碼

using System.Net.Quic;
using System.Net.Security;
using System.Net;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Buffers;
using System.Reflection.PortableExecutable;
using System.IO.Pipelines;
using System.Text;namespace ConsoleApp1
{internal class Program{[SupportedOSPlatform("linux")][SupportedOSPlatform("windows")][RequiresPreviewFeatures]static async Task Main(string[] args){// 創建 QuicListenervar listener = await QuicListener.ListenAsync(new QuicListenerOptions{ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3 },ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 9999),ConnectionOptionsCallback = (connection, ssl, token) => ValueTask.FromResult(new QuicServerConnectionOptions(){DefaultStreamErrorCode = 0,DefaultCloseErrorCode = 0,ServerAuthenticationOptions = new SslServerAuthenticationOptions(){ApplicationProtocols = new List<SslApplicationProtocol>() { SslApplicationProtocol.Http3 },ServerCertificate = GenerateManualCertificate()//生成證書}})});_ = Task.Run(async () =>{Console.WriteLine("Quic Client Running...");await Task.Delay(1000);// 連接到服務端var connection = await QuicConnection.ConnectAsync(new QuicClientConnectionOptions{DefaultCloseErrorCode = 0,DefaultStreamErrorCode = 0,RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 9999),ClientAuthenticationOptions = new SslClientAuthenticationOptions{ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http3 },RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>{return true;}}});// 打開一個出站的雙向流var stream = await connection.OpenOutboundStreamAsync(QuicStreamType.Bidirectional);stream.ReadTimeout = 16000;var reader = PipeReader.Create(stream);var writer = PipeWriter.Create(stream);// 后臺讀取流數據_ = ProcessLinesAsync(stream);Console.WriteLine();// 寫入數據for (int i = 0; i < 7; i++){await Task.Delay(2000);var message = $"Hello Quic {i} \n";Console.Write("Send -> " + message);await writer.WriteAsync(Encoding.UTF8.GetBytes(message));}await writer.CompleteAsync();Console.ReadKey();});var connection = await listener.AcceptConnectionAsync();Console.WriteLine($"Client [{connection.RemoteEndPoint}]: connected");var stream = await connection.AcceptInboundStreamAsync();Console.WriteLine($"Stream [{stream.Id}]: created");await ProcessLinesAsync(stream);}// 處理流數據[SupportedOSPlatform("linux")][SupportedOSPlatform("windows")][RequiresPreviewFeatures]static async Task ProcessLinesAsync(QuicStream stream){var reader = PipeReader.Create(stream);var writer = PipeWriter.Create(stream);while (true){ReadResult result = await reader.ReadAsync();ReadOnlySequence<byte> buffer = result.Buffer;while (TryReadLine(ref buffer, out ReadOnlySequence<byte> line)){// Process the line. ProcessLine(line);// Ack //await writer.WriteAsync(System.Text.Encoding.UTF8.GetBytes($"ack: {DateTime.Now.ToString("HH:mm:ss")} \n"));}// Tell the PipeReader how much of the buffer has been consumed.reader.AdvanceTo(buffer.Start, buffer.End);// Stop reading if there's no more data coming.if (result.IsCompleted){break;}}Console.WriteLine($"Stream [{stream.Id}]: completed");await reader.CompleteAsync();await writer.CompleteAsync();}static bool TryReadLine(ref ReadOnlySequence<byte> buffer, out ReadOnlySequence<byte> line){// Look for a EOL in the buffer.SequencePosition? position = buffer.PositionOf((byte)'\n');if (position == null){line = default;return false;}// Skip the line + the \n.line = buffer.Slice(0, position.Value);buffer = buffer.Slice(buffer.GetPosition(1, position.Value));return true;}static void ProcessLine(in ReadOnlySequence<byte> buffer){foreach (var segment in buffer){Console.WriteLine("Recevied -> " + System.Text.Encoding.UTF8.GetString(segment.Span));}Console.WriteLine();}static X509Certificate2 GenerateManualCertificate(){X509Certificate2 cert = null;var store = new X509Store("KestrelWebTransportCertificates", StoreLocation.CurrentUser);store.Open(OpenFlags.ReadWrite);if (store.Certificates.Count > 0){cert = store.Certificates[^1];// rotate key after it expiresif (DateTime.Parse(cert.GetExpirationDateString(), null) < DateTimeOffset.UtcNow){cert = null;}}if (cert == null){// generate a new certvar now = DateTimeOffset.UtcNow;SubjectAlternativeNameBuilder sanBuilder = new();sanBuilder.AddDnsName("localhost");using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256);CertificateRequest req = new("CN=localhost", ec, HashAlgorithmName.SHA256);// Adds purposereq.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection{new("1.3.6.1.5.5.7.3.1") // serverAuth}, false));// Adds usagereq.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));// Adds subject alternate namesreq.CertificateExtensions.Add(sanBuilder.Build());// Signusing var crt = req.CreateSelfSigned(now, now.AddDays(14)); // 14 days is the max duration of a certificate for thiscert = new(crt.Export(X509ContentType.Pfx));// Savestore.Add(cert);}store.Close();var hash = SHA256.HashData(cert.RawData);var certStr = Convert.ToBase64String(hash);//Console.WriteLine($"\n\n\n\n\nCertificate: {certStr}\n\n\n\n"); // <-- you will need to put this output into the JS API call to allow the connectionreturn cert;}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/44204.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/44204.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/44204.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【獨家揭秘】視頻號矩陣系統火爆上線,一鍵式多平臺管理,你的內容營銷神器!

在信息爆炸的時代&#xff0c;內容創作者們面臨著前所未有的挑戰與機遇。如何讓自己的內容在眾多平臺中脫穎而出&#xff0c;快速傳播并吸引大量觀眾&#xff0c;成為了每個創作者關注的焦點。近日&#xff0c;一款名為“迅狐視頻號矩陣系統”的神器震撼來襲&#xff0c;它以其…

UV膠,它是否有毒?如同那些隱藏在黑暗中的危險之物?

UV膠&#xff0c;它是否有毒&#xff1f;如同那些隱藏在黑暗中的危險之物&#xff1f; 關于uv膠的毒性問題&#xff0c;或許我們可以這樣深入探討。UV膠&#xff0c;如同一位戴著神秘面紗的訪客&#xff0c;在我們的生活中悄然出現&#xff0c;卻帶著諸多疑問。那么&#xff0…

二維碼生成需知:名片二維碼尺寸多少合適?電子名片二維碼制作方法?

隨著數字化時代的到來&#xff0c;二維碼在各個領域的應用越來越廣泛&#xff0c;名片作為商業交流的重要工具之一&#xff0c;也開始逐漸融入二維碼的元素。通過在名片上添加二維碼&#xff0c;我們可以輕松實現信息的快速傳遞和分享。然而&#xff0c;名片二維碼的尺寸選擇成…

Monorepo倉庫管理策略之 Lerna

這里寫目錄標題 前言&#xff1a;一、簡介二、新建項目使用安裝生成結構 三、復用現有項目執行命令查看包 四、配置package相互引用導入現有的包 五、發布包確定項目版本發布項目添加項目到到git發布包到NPM包發布出錯解決方案 五、實例代碼 前言&#xff1a; 將大型代碼倉庫分…

Python 與扣子 API的鏈接

當 Python 與各種 API 進行鏈接時&#xff0c;更是能碰撞出無數精彩的火花&#xff0c;為我們的開發工作帶來極大的便利和創新。今天&#xff0c;咱們就來聊聊 Python 與扣子 API 的鏈接那些事兒。 扣子 API 作為一種新興的技術接口&#xff0c;為我們提供了豐富的數據和功能。…

文心一言的流式接口數據進行處理 增加屬性

需求&#xff1a;需要對文心一言的流式接口數據進行處理 增加屬性 return ResponseEntity.ok().header("Access-Control-Allow-Origin", "*").contentType(org.springframework.http.MediaType.TEXT_EVENT_STREAM).cacheControl(org.springframework.http…

python調用串口收發數據

1、確認串口信息 2、安裝pyserial庫 打開終端或命令行&#xff0c;敲入這行命令&#xff1a;pip install pyserial 3、python編程 import serial def main(): #創建串口對象 ser serial.Serial(COM4, 9600, timeout1) if not ser.isOpen(): print("串…

飛睿智能6公里WiFi圖傳接收模塊,低延遲、抗干擾、高速穩定傳輸數據,無人機、農田遠距離WiFi模塊

在科技日新月異的今天&#xff0c;無線通信技術正以前所未有的速度發展&#xff0c;不僅改變了我們的生活方式&#xff0c;還為企業帶來了前所未有的商業機遇。今天&#xff0c;我要向大家介紹一款飛睿智能的產品——6公里WiFi圖傳接收模塊&#xff0c;它以其高性能、穩定的傳輸…

【常見的設計模式】單例模式

參考&#xff1a;【設計模式專題之單例模式】1.小明的購物車 【設計模式專題之單例模式】 1.小明的購物車 時間限制&#xff1a;1.000S 空間限制&#xff1a;256MB ? 題目描述 小明去了一家大型商場&#xff0c;拿到了一個購物車&#xff0c;并開始購物。請你設計一個購物車管…

【React】基礎數據回填--useForm與setFieldsValue詳解

相關屬性 1.form 2.setFieldsValue 代碼 import{Form }from"antd";const Publish =

體積大的快遞怎么寄便宜?如何寄件寄包裹更省錢?

大學畢業了&#xff0c;面對即將到來的工作生活&#xff0c;小李不得不把宿舍里的大包小包打包寄回家。可是&#xff0c;當他真正開始打包行李時&#xff0c;才發現這可不是一件簡單的事&#xff1a;衣服、被子、書籍、雜物……這些東西加起來體積不小&#xff0c;想要省錢寄快…

虛擬化技術 DeskV(或Desktop Virtualization)

DeskV&#xff08;或Desktop Virtualization&#xff09;&#xff0c;即桌面虛擬化技術&#xff0c;是一種將計算機的桌面系統&#xff08;包括操作系統、應用程序和用戶數據&#xff09;進行虛擬化&#xff0c;以實現桌面使用的安全性和靈活性的技術。以下是關于DeskV&#xf…

基于stm32單片機的智能手環的設計

摘 要 隨著科技的飛速發展和人們生活水平的提高&#xff0c;健康與科技日益融合&#xff0c;智能可穿戴設備已成為現代人生活中不可或缺的一部分。智能手環&#xff0c;作為一種便攜、實用且功能豐富的可穿戴設備&#xff0c;受到越來越多用戶的喜愛。它不僅能夠實時監測用戶的…

簡化嵌入式Linux開發:在Ubuntu上安裝和配置交叉編譯環境的高效方法

在嵌入式Linux開發中&#xff0c;我們通常需要在Ubuntu上安裝交叉編譯工具鏈&#xff0c;并配置相關文件。編譯過程中&#xff0c;如果遇到依賴庫問題&#xff0c;還需要手動查找并編譯開源源碼。這些步驟較為繁瑣&#xff0c;為了簡化操作&#xff0c;我們可以嘗試以下方案&am…

深度解析:銀行小額支付與大額支付的關鍵區別與應用場景

一、交易金額 小額支付&#xff1a;通常適用于金額在5萬元以下的支付場景。這種支付方式更適合個人用戶或小額交易場景&#xff0c;如便利店購物、支付停車費、小額匯款等。大額支付&#xff1a;涉及金額較大的支付交易&#xff0c;一般被定義為單筆交易金額超過一定數額&…

特殊的“user profile service服務登錄失”情況

記錄一下比較特殊的user profile service服務登錄失敗情況 公司電腦&#xff0c;某次之后每次來公司電腦開機后就會出現這個情況&#xff0c;后來發現只要是關機后再開機百分百出現&#xff0c;重啟就不會&#xff0c;一開始也百度、google了&#xff0c;網上有很多解決方式&am…

DropNotch for Mac v1.0.1 在 Mac 劉海快速使用 AirDrop

應用介紹 DropNotch 是一款專為Mac設計的應用程序&#xff0c;可以將MacBook的凹口區域&#xff08;劉海&#xff09;轉換為文件放置區。 功能特點 文件共享: 用戶可以將文件拖放到MacBook的凹口區域&#xff0c;并通過AirDrop、郵件、消息等方式輕松共享。多顯示器支持: 即…

.Net C#執行JavaScript腳本

文章目錄 前言一、安裝二、執行 JavaScript 腳本三、與腳本交互四、JS 調用 C# 方法五、多線程使用總結 前言 ClearScript 是一個 .NET 平臺下的開源庫&#xff0c;用于在 C# 和其他 .NET 語言中執行腳本代碼。它提供了一種方便和安全的方法來將腳本與應用程序集成&#xff0c;…

PHP酒店賓館民宿多商戶版系統小程序源碼

解鎖酒店新境界&#xff01;揭秘多商戶版系統的無限可能&#x1f3e8;? &#x1f680; 開篇&#xff1a;酒店業的新革命&#xff0c;多商戶版系統來襲&#xff01; 你是否夢想過將你的酒店打造成一個集餐飲、娛樂、購物于一體的綜合型休閑空間&#xff1f;現在&#xff0c;這…

【linux】服務器卸載cuda

【linux】服務器卸載cuda 文章目錄 【linux】服務器卸載cuda1、查找已安裝的 CUDA 包&#xff1a;2、卸載 CUDA&#xff1a;3、刪除殘留文件4、更新系統的包索引&#xff1a;5、檢查是否卸載干凈&#xff1a; 1、查找已安裝的 CUDA 包&#xff1a; dpkg -l | grep cuda2、卸載…