SpawnDev.BlazorJS.PeerJS 1.3.0

dotnet add package SpawnDev.BlazorJS.PeerJS --version 1.3.0                
NuGet\Install-Package SpawnDev.BlazorJS.PeerJS -Version 1.3.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SpawnDev.BlazorJS.PeerJS" Version="1.3.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SpawnDev.BlazorJS.PeerJS --version 1.3.0                
#r "nuget: SpawnDev.BlazorJS.PeerJS, 1.3.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install SpawnDev.BlazorJS.PeerJS as a Cake Addin
#addin nuget:?package=SpawnDev.BlazorJS.PeerJS&version=1.3.0

// Install SpawnDev.BlazorJS.PeerJS as a Cake Tool
#tool nuget:?package=SpawnDev.BlazorJS.PeerJS&version=1.3.0                

SpawnDev.BlazorJS.PeerJS

PeerJS simplifies peer-to-peer data, video, and audio calls.

NuGet version

SpawnDev.BlazorJS.PeerJS brings the amazing peerjs library to Blazor WebAssembly.

SpawnDev.BlazorJS.PeerJS uses SpawnDev.BlazorJS for Javascript interop allowing strongly typed, full usage of the peerjs Javascript library. Voice, video and data channels are all fully supported in Blazor WebAssembly. The SpawnDev.BlazorJS.PeerJS API is a strongly typed version of the API found at the peerjs repo.

Demo

Basic Demo

Setup

Create a new Blazor WebAssembly project
In the folder you created for your new project:

dotnet new blazorwasm

Add the Nuget package

dotnet add package SpawnDev.BlazorJS.PeerJS

Add BlazorJSRuntime service
Add to Program.cs

builder.Services.AddBlazorJSRuntime();

Add PeerJS Javascript Library
Add to index.html

<script src="_content/SpawnDev.BlazorJS.PeerJS/peerjs.min.js"></script>

(Alternatively await Peer.Init() can be used in C# to load the PeerJS library at runtime)

Create a Peer

var peer = new Peer("pick-an-id");
// You can pick your own id or omit the id if you want to get a random one from the server.

Data connections

Connect

var conn = peer.Connect("another-peers-id");
conn.OnOpen += () => {
  conn.Send("hi!");
};

Receive

peer.OnConnection += (DataConnection conn) => {
  conn.OnData += (JSObject data) => {
    // data is of type JSObject, which can be any type. imported as string here.
    // Will print 'hi!'
    Console.WriteLine(data.JSRefAs<string>());
  };
  conn.OnOpen += () => {
    conn.Send("hello!");
  };
};

Media calls

Call

using var navigator = JS.Get<Navigator>("navigator");
using var mediaDevices = navigator.MediaDevices;
using var stream = await mediaDevices.GetUserMedia(new { video = true, audio = true });
MediaConnection call = peer.Call("another-peers-id", stream);
call.OnStream += (MediaStream remoteStream) => {
  // Show stream in some <video> element.
};

Answer

peer.OnCall += async (MediaConnection call) => {
    using var navigator = JS.Get<Navigator>("navigator");
    using var mediaDevices = navigator.MediaDevices;
    using var stream = await mediaDevices.GetUserMedia(new { video = true, audio = true });
    call.Answer(stream); // Answer the call with an A/V stream.
    call.OnStream += (MediaStream remoteStream) => {
      // Show stream in some <video> element.
    };
};

Example

Modify the Blazor WASM Program.cs to initialize SpawnDev.BlazorJS for Javascript interop.
Example Program.cs

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using SpawnDev.BlazorJS;
using SpawnDev.BlazorJS.PeerJS.Demo;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// Add SpawnDev.BlazorJS interop
builder.Services.AddBlazorJSRuntime();
// Run app using BlazorJSRunAsync
await builder.Build().BlazorJSRunAsync();

Example Home.razor

@page "/"
@using SpawnDev.BlazorJS.JSObjects;
@using System.Text;
@using System.Text.Json;
@using SpawnDev.BlazorJS.JSObjects.WebRTC;
@implements IDisposable

<PageTitle>PeerJS Test</PageTitle>

<h1>PeerJS Test</h1>
<small>Open two windows and copy the ID from one to the other and click connect</small>
<br />
<a href target="_blank">Open in New Window</a>
<br />

<div>
    <input style="width: 350px;" @bind=@id readonly></input>
</div>
<div>
    <input placeholder="Remote Id" style="width: 350px;" @bind=@targetId></input>
    <button @onclick=@Connect>connect</button>
</div>
<div>
    <input placeholder="message" style="width: 350px;" @bind=@msg></input>
    <button @onclick=@Send>send</button>
</div>
<pre style="width: 600px; word-wrap: break-word; white-space: normal;">@((MarkupString)log)</pre>

@code {
    [Inject] BlazorJSRuntime JS { get; set; }
    Peer? peer = null;
    DataConnection? dataConnection = null;
    string id = "";
    string targetId = "";
    string msg = "";
    string log = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // Load the PeerJS Javascript library.
            // the library can be loaded in the index.html instead
            await Peer.Init();
            peer = new Peer();
            peer.OnOpen += Peer_OnOpen;
            peer.OnClose += Peer_OnClose;
            peer.OnError += Peer_OnError;
            peer.OnConnection += Peer_OnConnection;
            peer.OnCall += Peer_OnCall;
        }
    }

    void Log(string msg)
    {
        log += $"{msg}<br/>";
        StateHasChanged();
    }

    void Peer_OnConnection(DataConnection dataConnection)
    {
        Log("Peer_OnConnection");
        InitDataConnection(dataConnection);
    }

    void Peer_OnCall(MediaConnection mediaConnection)
    {
        Log($"Peer_OnCall: {mediaConnection.Type}");
    }

    void Connect()
    {
        if (peer == null) return;
        DisposeDataConnection();
        Log("Connect");
        InitDataConnection(peer.Connect(targetId));
    }

    void InitDataConnection(DataConnection dataConnection)
    {
        if (this.dataConnection != null) return;
        this.dataConnection = dataConnection;
        Log($"InitDataConnection: {dataConnection.Label}");
        dataConnection.OnOpen += DataConnection_OnOpen;
        dataConnection.OnClose += DataConnection_OnClose;
        dataConnection.OnData += DataConnection_OnData;
        dataConnection.OnError += DataConnection_OnError;
    }

    void DataConnection_OnData(JSObject msg)
    {
        if (msg.JSRef!.PropertyInstanceOf() == "String")
        {
            Log(">> " + msg.JSRef!.As<string>());
        }
        else
        {
            Log("DataConnection_OnData: non-string data");
        }
    }

    void DataConnection_OnOpen()
    {
        Log("DataConnection_OnOpen");
        Send($"Hello from {id}");
    }

    void DataConnection_OnClose()
    {
        Log("DataConnection_OnClose");
        DisposeDataConnection();
    }

    void DataConnection_OnError(PeerError error)
    {
        Log($"DataConnection_OnError: {error.Type}");
    }

    void DisposeDataConnection()
    {
        if (dataConnection != null)
        {
            dataConnection.OnOpen -= DataConnection_OnOpen;
            dataConnection.OnClose -= DataConnection_OnClose;
            dataConnection.OnData -= DataConnection_OnData;
            dataConnection.OnError -= DataConnection_OnError;
            dataConnection.Dispose();
            dataConnection = null;
        }
    }

    void Send(string msg)
    {
        if (dataConnection == null) return;
        dataConnection.Send(msg);
        Log($"<< {msg}");
    }

    void Send() => Send(msg);

    void Peer_OnOpen(string id)
    {
        this.id = id;
        Log($"Peer_OnOpen: {id}");
        StateHasChanged();
    }

    void Peer_OnClose()
    {
        Log("Peer_OnClose");
    }

    void Peer_OnError(PeerError error)
    {
        Log($"Peer_OnError: {error.Type}");
    }

    public void Dispose()
    {
        DisposeDataConnection();
        if (peer != null)
        {
            peer.OnOpen -= Peer_OnOpen;
            peer.OnClose -= Peer_OnClose;
            peer.OnError += Peer_OnError;
            peer.OnConnection -= Peer_OnConnection;
            peer.OnCall -= Peer_OnCall;
            peer.Destroy();
            peer.Dispose();
            peer = null;
        }
    }
}
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.3.0 108 7/26/2024
1.2.1 77 7/23/2024
1.2.0 79 7/17/2024
1.1.1 96 7/8/2024
1.1.0 101 6/19/2024
1.0.2 101 6/5/2024
1.0.1 96 6/3/2024
1.0.0 108 6/3/2024