.NET ヘルプ

C# WebRTC(開発者向けの仕組み)

更新済み 3月 6, 2024
共有:

WebRTC(ウェブ・アールティーシー) Web Real-Time Communication(Webリアルタイムコミュニケーション)の略称であり、初期の接続設定を除いて、データ転送のための中間サーバーを必要とせずに、ウェブブラウザおよび他のプラットフォーム間で直接、リアルタイムの通信を可能にする技術です。それはビデオ、音声、および一般的なデータをピア間で共有することをサポートしており、リアルタイムコミュニケーションアプリケーションを開発するための強力なツールです。

このチュートリアルでは、.NET Coreフレームワークに焦点を当てて、C#を使用してWebRTCソリューションを作成する方法を紹介し、シグナリングサーバーの設定、TURNサーバーの理解、WebRTCの統合に関する洞察を提供します。 IronPDF C# アプリケーション。

環境の設定

C#でWebRTCアプリケーションの開発を開始するには、開発環境を設定する必要があります。 これには、ウェブサイト、サービス、およびコンソールアプリを構築するためのクロスプラットフォームバージョンである.NET Coreのインストールが含まれます。.NET CoreはMicrosoftの公式ウェブサイトからダウンロードしてインストールすることができます。インストールが完了したら、人気の統合開発環境であるVisual Studioを使用できます。 (IDE (統合開発環境)) 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 API などのメッセージ伝送メカニズムを介してシグナリングを実装することができます。

.NET Coreでシグナリングサーバーを実装する

シグナリングサーバーは、直接のピアツーピア接続が確立される前に、ピア間でメッセージを交換するための仲介役を果たします。 .NET Coreを使用してシグナリングサーバーを実装するには、WebSocket接続を処理するシンプルなWebアプリケーションを作成します。

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#

以下のコードスニペットは、アプリにリアルタイムWeb機能を追加するためのライブラリであるSignalRを使用して、基本的な.NET Coreアプリケーションをセットアップします。SignalRはリアルタイムWeb機能をアプリケーションに追加するプロセスを簡素化し、シグナリングサーバーとして適した選択肢となります。

WebRTCを使用したピア接続

シグナリングサーバーを設定した後、次のステップはWebRTCを使用してクライアント間のピアツーピア接続を確立することです。 これは、各クライアントでRTCPeerConnectionオブジェクトを作成し、オファーメッセージとアンサーメッセージを交換し、接続の詳細を交渉することを含みます。

ピア接続の作成

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#

.NETアプリケーションへのWebRTCの統合

コアのWebRTC実装は通常、ブラウザやその他のクライアント側環境で処理されますが、.NETアプリケーションはシグナリングプロセスを促進し、セッション制御を管理し、NATトラバーサルのためのTURNサーバーなどの他のサービスと連携することができます。 デスクトップまたはサーバーサイドアプリケーションの場合、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#

このコマンドは、アプリケーションをコンパイルして実行し、実装したシグナリングサーバーを起動します。 あなたのWebクライアントは、今このサーバーに接続してシグナリングメッセージの交換を開始できます。

IronPDFの紹介

C# WebRTC (ウェブRTC) (開発者のための動作原理): 図1 - IronPDFウェブページ

IronPDF は、PDF生成および操作機能を.NETアプリケーションに提供する多用途のライブラリであり、開発者がプログラムで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.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >