.NET 幫助

C# WebRTC(開發人員如何運作)

發佈 2024年3月6日
分享:

WebRTC 代表Web實時通信,一種技術可以使網頁瀏覽器和其他平台之間進行直接、實時的通信,而無需中間伺服器來進行數據傳輸,除了初始連接設置。它支持視頻、音頻和通用數據在對等端之間共享,使其成為開發實時通信應用程序的強大工具。

本教程介紹了如何使用C#創建WebRTC解決方案,重點是.NET Core框架,並提供了設置信令伺服器、理解TURN伺服器以及將WebRTC集成到您的 IronPDF C# 應用程式。

設置您的環境

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

建立一個新的控制台應用程式

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

dotnet new console -n WebRTCSample
dotnet new console -n WebRTCSample
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet New console -n WebRTCSample
VB   C#

這個命令會建立一個名為 WebRTCSample 的新目錄,其中包含一個簡單的「Hello World」控制台應用程式。進入你的專案目錄,你就可以開始進行 WebRTC 應用程式的編碼了。

理解 WebRTC 和信令

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

在 .NET Core 中實現訊號伺服器

訊號伺服器作為中介,在建立直接的點對點連接之前交換訊息。您可以通過創建一個處理 WebSocket 連接的簡單網頁應用程式,使用 .NET Core 實現訊號伺服器。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddDefaultPolicy(
            builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
        services.AddSignalR();
    }
    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
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options => options.AddDefaultPolicy(
            builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
        services.AddSignalR();
    }
    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
	Public Sub ConfigureServices(ByVal services As IServiceCollection)
		services.AddCors(Function(options) options.AddDefaultPolicy(Function(builder) builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()))
		services.AddSignalR()
	End Sub
	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
VB   C#

這段程式碼片段設置了一個帶有 SignalR 的基本 .NET Core 應用程式,SignalR 是一個為應用程式添加即時網路功能的庫。SignalR 簡化了將即時網路功能添加到應用程式的過程,因而成為我們信號伺服器的理想選擇。

使用 WebRTC 連接對等方

在設定好信令伺服器後,下一步是使用 WebRTC 在客戶端之間建立點對點連接。這需要在每個客戶端上創建 RTCPeerConnection 對象,交換 offer 和 answer 訊息,並協商連接的詳細資訊。

創建對等連接

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

const peerConnection = new RTCPeerConnection();
peerConnection.onicecandidate = event => {
  if (event.candidate) {
    sendMessage('new-ice-candidate', event.candidate);
  }
};
peerConnection.ontrack = event => {
  // Display the video or audio stream
};
const peerConnection = new RTCPeerConnection();
peerConnection.onicecandidate = event => {
  if (event.candidate) {
    sendMessage('new-ice-candidate', event.candidate);
  }
};
peerConnection.ontrack = event => {
  // Display the video or audio stream
};
Private const peerConnection = New RTCPeerConnection()
'INSTANT VB TODO TASK: VB does not allow assigning to events in the event declaration:
onicecandidate = event => Implements peerConnection.onicecandidate
  If event.candidate Then
	sendMessage( 'New-ice-candidate', event.candidate);
  End If
	RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
	End RaiseEvent
End Event
'INSTANT VB TODO TASK: VB does not allow assigning to events in the event declaration:
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
ontrack = event => Implements peerConnection.ontrack
VB   C#

這段 JavaScript 程式碼片段展示了如何創建新的點對點連接、處理 ICE 候選者,並設置回調以顯示傳入的媒體流。

交換邀約和應答

為了建立連接,一方創建邀約,而另一方回應應答。這些訊息通過前面實現的信令服務器進行交換。

async function createOffer() {
  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);
  sendMessage('offer', offer);
}
async function createAnswer(offer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  const answer = await peerConnection.createAnswer();
  await peerConnection.setLocalDescription(answer);
  sendMessage('answer', answer);
}
async function createOffer() {
  const offer = await peerConnection.createOffer();
  await peerConnection.setLocalDescription(offer);
  sendMessage('offer', offer);
}
async function createAnswer(offer) {
  await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
  const answer = await peerConnection.createAnswer();
  await peerConnection.setLocalDescription(answer);
  sendMessage('answer', answer);
}
Async Function createOffer() As [function]
  const offer = Await peerConnection.createOffer()
  Await peerConnection.setLocalDescription(offer)
  sendMessage( 'offer', offer);
End Function
Async Function createAnswer(ByVal As offer) As [function]
  Await peerConnection.setRemoteDescription(New RTCSessionDescription(offer))
  const answer = Await peerConnection.createAnswer()
  Await peerConnection.setLocalDescription(answer)
  sendMessage( 'answer', answer);
End Function
VB   C#

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

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

執行您的應用程序

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

dotnet run
dotnet run
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet run
VB   C#

此命令會編譯並執行您的應用程式,啟動您已實現的信令伺服器。您的網頁客戶端現在可以連接到此伺服器以開始交換信令訊息。

IronPDF 介紹

C# WebRTC(開發人員如何運作):圖 1 - IronPDF 網頁

IronPDF 是一個多功能的函式庫,為 .NET 應用程序帶來PDF生成和操作能力,允許開發者以程序方式創建、閱讀和編輯PDF文件。IronPDF 支持一系列任務,包括生成 從 HTML 生成 PDF, 填寫表單,提取文本和保護文件。這使它在生成報告,發票和基於用戶數據或應用程序輸出的動態文件方面非常有用。

IronPDF的一個關鍵特點是其 HTML 轉 PDF 功能,保持您的佈局和樣式完整。它可以從網頁內容生成PDF,非常適合報告、發票和文件。您可以輕鬆地將HTML文件、URL和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
VB   C#

安裝 IronPDF

在您的專案中使用 IronPDF 之前,您需要將其添加到您的 .NET 應用程式中。這可以使用 NuGet 套件管理器來完成,它簡化了在您的專案中管理外部程式庫的過程。要安裝 IronPDF,您可以在 NuGet 套件管理器主控台中使用以下命令:

Install-Package IronPdf

用例:使用 IronPDF 在 WebRTC 應用程式中生成會議記錄 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
VB   C#

結論

C# WebRTC(開發人員如何運作):圖2 - IronPDF 授權頁面

在本文中,我們探討了如何使用 C# 和 .NET Core 創建一個基本的 WebRTC 應用程序。我們涵蓋了設置開發環境、創建新控制台應用程序、實現信令伺服器以及啟動對等連接以進行即時通訊。WebRTC 為即時通訊應用程序開啟了無數可能性,並且使用 C# 和 .NET Core,你可以構建跨不同平台和設備運行的強大且可擴展的解決方案。 IronPDF 適用於生產環境。一旦決定購買,該許可證從 $749 開始。

< 上一頁
Opentelemetry C#(開發人員如何使用)
下一個 >
C# OAuth2(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >