跳過到頁腳內容
.NET幫助

C# WebRTC(對於開發者的運行原理)

WebRTC 代表網頁即時通訊,這是一種技術,可使網頁瀏覽器和其他平台之間進行直接即時通訊,而不需要中介服務器進行數據傳輸,僅需在初始連接設置時使用。它支持在對等體之間共享視頻、音頻和通用數據,使其成為開發即時通訊應用程序的強大工具。

這篇教程介紹了如何使用 C# 創建 WebRTC 解決方案,重點是在 .NET Core 框架上,並提供了設置信號服務器、了解 TURN 服務器以及將 WebRTC 集成到您的 IronPDF C# 應用程序中的見解。

設置您的環境

要開始在 C# 中開發 WebRTC 應用程序,您需要設置開發環境。 這涉及安裝 .NET Core,它是 .NET 的跨平台版本,用於構建網站、服務和控制台應用程序。您可以從微軟的官方網站下載並安裝 .NET Core。安裝完成後,您可以使用 Visual Studio(C# 開發流行的集成開發環境 IDE)或選擇使用其他任何編輯器來編寫代碼。

創建新的控制台應用程序

首先設置一個新的控制台應用程序項目。 打開終端或命令行界面,並移動到您計劃建立項目的目錄。 接下來,執行以下命令:

dotnet new console -n WebRTCSample
dotnet new console -n WebRTCSample
SHELL

此命令會創建一個名為 WebRTCSample 的新目錄,其中包含一個簡單的 "Hello World" 控制台應用程序。 導航到您的項目目錄,您就可以開始編寫您的 WebRTC 應用了。

理解 WebRTC 和信令

WebRTC 使即時通訊成為可能,但需要一種機制來協調通訊和發送控制消息,這一過程被稱為信令。 信令用於交換關於通信會話的元數據,例如建立連接的會話描述和候選信息。 C# 應用程序可以通過任何消息傳輸機制實現信令,如 WebSockets 或 REST API。

在 .NET Core 中實現信令服務器

信令服務器在建立直接對等連接之前,充當中介來交換對等體之間的消息。 您可以通過創建一個簡單的 Web 應用程序來用 .NET Core 實現信令服務器,該應用程序處理 WebSocket 連接。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    // Configures services for the web application.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddDefaultPolicy(
            builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
        services.AddSignalR();
    }

    // Configures the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<SignalingHub>("/signal");
        });
    }
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public class Startup
{
    // Configures services for the web application.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddDefaultPolicy(
            builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
        services.AddSignalR();
    }

    // Configures the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<SignalingHub>("/signal");
        });
    }
}
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Hosting
Imports Microsoft.Extensions.DependencyInjection
Imports Microsoft.Extensions.Hosting

Public Class Startup
	' Configures services for the web application.
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		services.AddCors(Function(options) options.AddDefaultPolicy(Function(builder) builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()))
		services.AddSignalR()
	End Sub

	' Configures the HTTP request pipeline.
	Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
		If env.IsDevelopment() Then
			app.UseDeveloperExceptionPage()
		End If
		app.UseCors()
		app.UseRouting()
		app.UseEndpoints(Sub(endpoints)
			endpoints.MapHub(Of SignalingHub)("/signal")
		End Sub)
	End Sub
End Class
$vbLabelText   $csharpLabel

此代碼片段設置了一個帶有 SignalR 的基本 .NET Core 應用程序,這是一個為應用程序增加即時 Web 功能的庫。SignalR 簡化了為應用程序添加即時 Web 功能的過程,使其成為我們的信令服務器的理想選擇。

通過 WebRTC 連接對等體

設置信令服務器後,下一步是使用 WebRTC 建立客戶端之間的對等連接。 這涉及在每個客戶端上創建 RTCPeerConnection 對象,交換報價和答案消息,協商連接細節。

創建對等連接

在您的 C# 應用程序中,您將主要管理信令部分,並可能通過瀏覽器或其他平台(如移動應用程序的 React Native)與 WebRTC API 交互。以下是如何從 Web 客戶端啟動對等連接的示例:

// Create a new RTCPeerConnection instance
const peerConnection = new RTCPeerConnection();

// Listen for ICE candidates and send them to the signaling server
peerConnection.onicecandidate = event => {
  if (event.candidate) {
    sendMessage('new-ice-candidate', event.candidate);
  }
};

// Handle incoming media streams
peerConnection.ontrack = event => {
  // Display the video or audio stream
};
// Create a new RTCPeerConnection instance
const peerConnection = new RTCPeerConnection();

// Listen for ICE candidates and send them to the signaling server
peerConnection.onicecandidate = event => {
  if (event.candidate) {
    sendMessage('new-ice-candidate', event.candidate);
  }
};

// Handle incoming media streams
peerConnection.ontrack = event => {
  // Display the video or audio stream
};
JAVASCRIPT

此 JavaScript 代碼片段演示了創建新對等連接、處理 ICE 候選項和設置回調以顯示傳入的媒體流的過程。

交換報價和答案

要建立連接,必須由一個對等體創建報價,另一個對等體則需回復答复。 這些通過之前實現的信令服務器交換。

// Create an offer for the peer connection
async function createOffer() {
  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);
  sendMessage('offer', offer);
}

// Create an answer after receiving an offer
async function createAnswer(offer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  const answer = await peerConnection.createAnswer();
  await peerConnection.setLocalDescription(answer);
  sendMessage('answer', answer);
}
// Create an offer for the peer connection
async function createOffer() {
  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);
  sendMessage('offer', offer);
}

// Create an answer after receiving an offer
async function createAnswer(offer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  const answer = await peerConnection.createAnswer();
  await peerConnection.setLocalDescription(answer);
  sendMessage('answer', answer);
}
JAVASCRIPT

將 WebRTC 集成到 .NET 應用程序中

雖然核心 WebRTC 實現通常在瀏覽器或其他客戶端環境中處理,但 .NET 應用程序可以促進信令過程,管理會話控制,並與其他服務(如 NAT 穿越的 TURN 服務器)交互。 對於桌面或服務器端應用程序,可以封裝 Pion WebRTC(用於 Go 的開源庫)或與 C# 搭配使用來處理 WebRTC 流量。

運行您的應用程序

要運行您的 .NET Core 應用程序,請在終端導航到項目目錄並執行:

dotnet run
dotnet run
SHELL

此命令編譯並運行您的應用程序,啟動您實現的信令服務器。 您的 Web客戶端現在可以連接到此服務器開始交換信令消息。

IronPDF 简介

C# WebRTC(開發人員的運作方式):圖 1 - IronPDF 網頁

IronPDF 是一個多功能庫,將 PDF 生成和操作功能帶到 .NET 應用程序,允許開發人員以編程方式創建、閱讀和編輯 PDF 文檔。 IronPDF 支持一系列任務,包括從註冊表 從 HTML 生成 PDF、填寫表單、提取文本以及保障文檔安全。 這使其在根據用戶數據或應用程序輸出生成報告、發票和動態文檔時特別有用。

IronPDF 的一個關鍵功能是其 HTML 到 PDF 功能,保持您的布局和樣式不變。 它從網頁內容生成 PDF,非常適合報告、發票和文檔。 您可以輕鬆將 HTML 文件、網址、HTML 字串轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

安裝 IronPDF

在項目中使用 IronPDF 之前,您需要將其添加到您的 .NET 應用程序中。 這可以使用 NuGet 包管理器完成,它簡化了在項目中管理外部庫的過程。 您可以在 NuGet 包管理器控制台中使用以下命令安裝 IronPDF:

Install-Package IronPdf

用例:在 WebRTC 應用程序中使用 IronPDF 生成會議記錄 PDF

想像一下開發一個使用 WebRTC 的即時通訊應用程序,旨在用於在線會議或虛擬課堂。 該應用程序允許用戶參加音視頻通話、共享屏幕並即時協作處理文檔。此應用程序的一個有價值的功能將是能夠自動生成並分發會議記錄或會議摘要,其中包括會議中討論的重點、做出的決定和行動項,以 PDF 格式呈現。 這就是 IronPDF 派上用場的地方。

實現步驟

  1. 捕獲會議內容:在 WebRTC 會議過程中,捕獲文本為基的內容,例如聊天信息、共享筆記或突出顯示的行動項目。 此內容可以格式化為 HTML,從而可以輕鬆進行樣式設計和組織(例如,使用列表列出行動項目,並使用標題呈現關鍵主題)。
  2. 生成 HTML 範本:會議結束時,將捕獲的內容格式化為 HTML 範本。 該範本包括會議的標題、日期、參與者以及針對不同類型內容(討論點、決策、行動事項)的結構化部分。
  3. 將 HTML 轉換為 PDF:一旦會議結束並準備好 HTML 模板,IronPDF 用於將此 HTML 內容轉換為 PDF 文檔。 此轉換確保了 HTML 中定義的樣式和佈局在 PDF 中得到保留,使該文檔易於閱讀且具有專業外觀。

這是一個示例 PDF 代碼:

using IronPdf;

public class MeetingMinutesGenerator
{
    public static void GenerateMeetingMinutesPdf(string htmlContent, string outputPath)
    {
        // Initialize the HTML to PDF converter
        var renderer = new HtmlToPdf();
        renderer.PrintOptions.MarginTop = 40;
        renderer.PrintOptions.MarginBottom = 40;
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            CenterText = "{pdf-title}",
            DrawDividerLine = true,
            FontSize = 12
        };
        renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
        {
            LeftText = "{date} {time}",
            RightText = "Page {page} of {total-pages}",
            DrawDividerLine = true,
            FontSize = 12
        };
        // Convert the HTML content to a PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF document
        pdfDocument.SaveAs(outputPath);
        Console.WriteLine("Meeting minutes PDF generated.");
    }
}
using IronPdf;

public class MeetingMinutesGenerator
{
    public static void GenerateMeetingMinutesPdf(string htmlContent, string outputPath)
    {
        // Initialize the HTML to PDF converter
        var renderer = new HtmlToPdf();
        renderer.PrintOptions.MarginTop = 40;
        renderer.PrintOptions.MarginBottom = 40;
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            CenterText = "{pdf-title}",
            DrawDividerLine = true,
            FontSize = 12
        };
        renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
        {
            LeftText = "{date} {time}",
            RightText = "Page {page} of {total-pages}",
            DrawDividerLine = true,
            FontSize = 12
        };
        // Convert the HTML content to a PDF document
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF document
        pdfDocument.SaveAs(outputPath);
        Console.WriteLine("Meeting minutes PDF generated.");
    }
}
Imports IronPdf

Public Class MeetingMinutesGenerator
	Public Shared Sub GenerateMeetingMinutesPdf(ByVal htmlContent As String, ByVal outputPath As String)
		' Initialize the HTML to PDF converter
		Dim renderer = New HtmlToPdf()
		renderer.PrintOptions.MarginTop = 40
		renderer.PrintOptions.MarginBottom = 40
		renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {
			.CenterText = "{pdf-title}",
			.DrawDividerLine = True,
			.FontSize = 12
		}
		renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {
			.LeftText = "{date} {time}",
			.RightText = "Page {page} of {total-pages}",
			.DrawDividerLine = True,
			.FontSize = 12
		}
		' Convert the HTML content to a PDF document
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF document
		pdfDocument.SaveAs(outputPath)
		Console.WriteLine("Meeting minutes PDF generated.")
	End Sub
End Class
$vbLabelText   $csharpLabel

結論

C# WebRTC(開發人員的工作方式):圖 2 - IronPDF 授權頁面

在這篇文章中,我們探討了使用 C# 和 .NET Core 創建基本 WebRTC 應用程序的過程。 我們涵蓋了設置開發環境、創建新控制台應用程序、實現信令服務器和為即時通信啟動對等連接的過程。 WebRTC 為即時通訊應用程序開創了許多可能性,通過 C# 和 .NET Core,您可以構建跨不同平台和設備運行的穩健且可擴展的解決方案。 有關授權和購買的信息,請訪問 IronPDF 授權頁面。 一旦您決定購買,許可證從 $799 起。

常見問題解答

使用 WebRTC 與 C# 及 .NET Core 有什麼好處?

WebRTC 結合 C# 與 .NET Core 可以讓開發人員創建實時通訊應用程式,利用 WebRTC 和 C# 開發環境的強大功能。這種組合支持直接對等數據傳輸,並且可以與像 IronPDF 這樣的 .NET 庫整合以增加功能。

我如何設置 C# 的 WebRTC 開發環境?

要設置 WebRTC 的 C# 開發環境,您需要從 Microsoft 官方網站安裝 .NET Core SDK。使用如 Visual Studio 之類的整合開發環境高效地管理和編寫代碼。這樣的設置將允許您創建控制台應用程式並整合 WebRTC 功能。

訊號伺服器在 WebRTC 應用程式中扮演什麼角色?

訊號伺服器在 WebRTC 應用程式中非常重要,因為它促進了控制訊息和元數據在對等方之間的交換,以建立連接。它有助於在建立直接對等連接之前,協商會話描述和候選資訊。

如何使用 .NET Core 創建訊號伺服器?

您可以透過開發管理 WebSocket 連接的簡單網頁應用以使用 .NET Core 創建訊號伺服器。利用 SignalR(一個增加實時網頁功能的庫)能夠簡化實施訊號伺服器的過程。

如何在 WebRTC 應用程式中使用 IronPDF 生成 PDF?

IronPDF 能夠整合進入 WebRTC 應用程式,從 HTML 內容生成 PDF。這尤其有助於創建會議紀要或會話摘要等文件,提高實時通訊應用程式的功能。

建立 WebRTC 中的點對點連接涉及哪些步驟?

在 WebRTC 中建立點對點連接涉及創建 RTCPeerConnection 對象,交換 offer 和 answer 訊息,並使用 ICE 候選協商連接詳情。這個過程對於啟用對等方之間的直接通訊至關重要。

TURN 伺服器如何促進 WebRTC 連接?

當直接連接不可行時,TURN 伺服器通過在對等方之間中繼媒體來協助啟用 WebRTC 連接,特別是在限制性網絡環境中。這確保了在需要 NAT 穿越的情況下仍然能夠建立連接。

HTML 可以在 .NET 應用程式中轉換為 PDF 嗎?

是的,HTML 可以在 .NET 應用程式中使用像 IronPDF 這樣的庫轉換為 PDF。像 RenderHtmlAsPdf 這樣的方法可以用來將 HTML 內容轉換為 PDF 文件,同時保留原有的樣式和佈局。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。