在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
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
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet New console -n WebRTCSample
這個命令創建了一個名為WebRTCSample的新目錄,並包含一個簡單的 "Hello World" 控制台應用程式。 進入你的專案目錄後,你就可以開始編寫你的 WebRTC 應用了。
WebRTC 使即時通訊成為可能,但它需要一個機制來協調通信和發送控制訊息,這個過程稱為信令。 信令用於交換有關通信會話的元數據,例如會話描述和用於建立連接的候選信息。 C# 應用程式可以通過任何消息傳輸機制實現訊號傳遞,例如 WebSockets 或 REST API。
訊號伺服器作為仲介,在建立直接點對點連接之前交換點與點之間的消息。 您可以使用.NET Core來實現信令伺服器,通過創建一個處理WebSocket連接的簡單網路應用程式。
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
這段程式碼片段設置了一個帶有 SignalR 的基本 .NET Core 應用程式,SignalR 是一個為應用程式添加即時網路功能的庫。SignalR 簡化了將即時網路功能添加到應用程式的過程,因而成為我們信號伺服器的理想選擇。
在設置信令伺服器之後,下一步是使用 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
這段 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
雖然核心的 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
此命令編譯並運行您的應用程式,啟動您已實現的信令伺服器。 您的網頁客戶端現在可以連接到此伺服器以開始交換信令消息。
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
在您可以在專案中使用IronPDF之前,您需要將其添加到您的.NET應用程式中。 這可以使用 NuGet 套件管理器來完成,它簡化了在專案中管理外部庫的過程。 要安裝IronPDF,您可以在NuGet套件管理器控制台中使用以下命令:
Install-Package IronPdf
想像一下,使用 WebRTC 開發一個即時通訊應用程式,專為線上會議或虛擬課堂而設計。 這個應用程式允許用戶進行音頻和視頻通話、共享螢幕,並實時協作處理文件。這個應用程式的一個有價值的功能是能夠自動生成並分發會議紀要或會議摘要,包括討論的要點、做出的決定和行動項目,以 PDF 格式呈現。 這就是 IronPDF 發揮作用的地方。
捕捉會議內容:在 WebRTC 會議過程中,文字內容如聊天信息、共享筆記或標記的行動項目都將被捕捉。 此內容可格式化為 HTML,允許輕鬆進行樣式和組織(例如,使用清單列出行動項目和標題列出關鍵主題)。
生成 HTML 範本:在會議結束時,抓取的內容會被格式化為 HTML 範本。 此範本包含會議的標題、日期、參加者,以及針對不同類型內容(討論要點、決策、行動項目)結構化的部分。
將 HTML 轉換成 PDF:會議結束後,準備好 HTML 模板,就可以使用 IronPDF 將這些 HTML 內容轉換成 PDF 文件。 此轉換確保 PDF 保留了 HTML 中定義的樣式和佈局,使文件易於閱讀並具備專業外觀。
以下是一個範例 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
在本文中,我們探討了如何使用 C# 和 .NET Core 創建一個基本的 WebRTC 應用程式。 我們涵蓋了設置開發環境、創建新的控制台應用程式、實施信令伺服器以及啟動對等連接以進行實時通訊。 WebRTC 為即時通訊應用程序開啟了諸多可能性,使用 C# 和 .NET Core,您可以構建跨不同平台和設備運行的健壯且可擴展的解決方案。 有關授權和購買資訊,請造訪IronPDF 授權頁面。 一旦您決定購買,授權從$749開始。