.NET ヘルプ

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

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

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

環境の設定

C#でWebRTCアプリケーションの開発を開始するには、開発環境を設定する必要があります。 これは、.NET Coreをインストールすることを含みます。.NET Coreはウェブサイト、サービス、コンソールアプリを構築するためのクロスプラットフォームバージョンの.NETです。.NET CoreはMicrosoftの公式ウェブサイトからダウンロードしてインストールできます。インストールが完了したら、C#開発用の一般的な統合開発環境(IDE)であるVisual Studioや、その他お好みのエディターを使用してコードを書くことができます。

新しいコンソールアプリケーションの作成

新しいコンソールアプリケーションプロジェクトを設定することから始めましょう。 ターミナルまたはコマンドラインインターフェイスを開き、プロジェクトを設定したいディレクトリに移動します。 次に、以下のコマンドを実行してください:

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
$vbLabelText   $csharpLabel

このコマンドは、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
$vbLabelText   $csharpLabel

以下のコードスニペットは、アプリにリアルタイム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
$vbLabelText   $csharpLabel

この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
$vbLabelText   $csharpLabel

.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
$vbLabelText   $csharpLabel

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

IronPDFの紹介

C# WebRTC(開発者向けの仕組み):図1 - IronPDFウェブページ

IronPDFは、.NETアプリケーションにPDFの生成および操作機能を提供する多用途なライブラリであり、開発者がプログラムでPDFドキュメントを作成、読み取り、編集することを可能にします。 IronPDFは、HTMLからのPDF生成、フォームの入力、テキストの抽出、ドキュメントの保護を含む様々なタスクをサポートします。 これは、ユーザーデータやアプリケーションの出力に基づいてレポート、請求書、および動的なドキュメントを生成するのに非常に役立ちます。

IronPDFの重要な機能の1つは、レイアウトとスタイルをそのままに保つHTML to 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

結論

C# WebRTC (開発者向けの仕組み): 図2 - IronPDF ライセンスページ

この記事では、C# と .NET Core を使用して基本的な WebRTC アプリケーションを作成する方法について探りました。 開発環境の設定、新しいコンソールアプリケーションの作成、シグナリングサーバーの実装、およびリアルタイムコミュニケーションのためのピア接続の開始について説明しました。 WebRTCはリアルタイムコミュニケーションアプリケーションに多くの可能性を提供し、C#および.NET Coreを使用することで、異なるプラットフォームやデバイスで動作する堅牢でスケーラブルなソリューションを構築できます。 ライセンスと購入情報については、IronPDFライセンスページをご覧ください。 購入を決定すると、ライセンスは$749から始まります。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
Opentelemetry C#(開発者向けの仕組み)
次へ >
C# OAuth2(開発者向けの動作説明)