• Stars
    star
    107
  • Rank 312,276 (Top 7 %)
  • Language
    C#
  • License
    MIT License
  • Created about 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pusher Channels Client Library for .NET

Pusher Channels .NET Client library

NuGet Badge Build

This is the official .NET library for interacting with the Channels WebSocket API.

Register at pusher.com/channels and use the application credentials within your app as shown below.

More general documentation can be found on the Official Channels Documentation.

For integrating Pusher Channels with Unity follow the instructions at https://github.com/pusher/pusher-websocket-unity

Supported platforms

⚠️ we recently released a major version -- if you are coming from version 1.x, please see the migration section

Contents

Installation

The compiled library is available on NuGet:

Install-Package PusherClient

API

Overview

Here's the API in a nutshell.

class ChatMember
{
    public string Name { get; set; }
}

class ChatMessage : ChatMember
{
    public string Message { get; set; }
}

// Raised when Pusher is ready
AutoResetEvent readyEvent = new AutoResetEvent(false);

// Raised when Pusher is done
AutoResetEvent doneEvent = new AutoResetEvent(false);

// Create Pusher client ready to subscribe to public, private and presence channels
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
    Encrypted = true,
});

// Lists all current presence channel members
void ListMembers(GenericPresenceChannel<ChatMember> channel)
{
    Dictionary<string, ChatMember> members = channel.GetMembers();
    foreach (var member in members)
    {
        Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}");
    }
}

// MemberAdded event handler
void ChatMemberAdded(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has joined");
    if (sender is GenericPresenceChannel<ChatMember> channel)
    {
        ListMembers(channel);
    }
}

// MemberRemoved event handler
void ChatMemberRemoved(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has left");
    if (sender is GenericPresenceChannel<ChatMember> channel)
    {
        ListMembers(channel);
    }
}

// Handle errors
void HandleError(object sender, PusherException error)
{
    if ((int)error.PusherCode < 5000)
    {
        // Error recevied from Pusher cluster, use PusherCode to filter.
    }
    else
    {
        if (error is ChannelUnauthorizedException unauthorizedAccess)
        {
            // Private and Presence channel failed authorization with Forbidden (403)
        }
        else if (error is ChannelAuthorizationFailureException httpError)
        {
            // Authorization endpoint returned an HTTP error other than Forbidden (403)
        }
        else if (error is OperationTimeoutException timeoutError)
        {
            // A client operation has timed-out. Governed by PusherOptions.ClientTimeout
        }
        else if (error is ChannelDecryptionException decryptionError)
        {
            // Failed to decrypt the data for a private encrypted channel
        }
        else
        {
            // Handle other errors
        }
    }

    Trace.TraceError($"{error}");
}

// Subscribed event handler
void SubscribedHandler(object sender, Channel channel)
{
    if (channel is GenericPresenceChannel<ChatMember> presenceChannel)
    {
        ListMembers(presenceChannel);
    }
    else if (channel.Name == "private-chat-channel-1")
    {
        // Trigger event
        channel.Trigger("client-chat-event", new ChatMessage
        {
            Name = "Joe",
            Message = "Hello from Joe!",
        });
    }
}

// Connection state change event handler
void StateChangedEventHandler(object sender, ConnectionState state)
{
    Trace.TraceInformation($"SocketId: {((Pusher)sender).SocketID}, State: {state}");
    if (state == ConnectionState.Connected)
    {
        readyEvent.Set();
        readyEvent.Reset();
    }
    if (state == ConnectionState.Disconnected)
    {
        doneEvent.Set();
        doneEvent.Reset();
    }
}

// Bind events
void BindEvents(object sender)
{
    Pusher _pusher = sender as Pusher;
    Channel _channel = _pusher.GetChannel("private-chat-channel-1");
    _channel.Bind("client-chat-event", (PusherEvent eventData) =>
    {
        ChatMessage data = JsonConvert.DeserializeObject<ChatMessage>(eventData.Data);
        Trace.TraceInformation($"[{data.Name}] {data.Message}");
    });
}

// Unbind events
void UnbindEvents(object sender)
{
    ((Pusher)sender).UnbindAll();
}

// Add event handlers
pusher.Connected += BindEvents;
pusher.Disconnected += UnbindEvents;
pusher.Subscribed += SubscribedHandler;
pusher.ConnectionStateChanged += StateChangedEventHandler;
pusher.Error += HandleError;

// Create subscriptions
await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false);
await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false);
GenericPresenceChannel<ChatMember> memberChannel =
    await pusher.SubscribePresenceAsync<ChatMember>("presence-channel-1").ConfigureAwait(false);
memberChannel.MemberAdded += ChatMemberAdded;
memberChannel.MemberRemoved += ChatMemberRemoved;

// Connect
try
{
    await pusher.ConnectAsync().ConfigureAwait(false);
}
catch (Exception)
{
    // We failed to connect, handle the error.
    // You will also receive the error via
    // HandleError(object sender, PusherException error)
    throw;
}

Assert.AreEqual(ConnectionState.Connected, pusher.State);
Assert.IsTrue(readyEvent.WaitOne(TimeSpan.FromSeconds(5)));

// Remove subscriptions
await pusher.UnsubscribeAllAsync().ConfigureAwait(false);

// Disconnect
await pusher.DisconnectAsync().ConfigureAwait(false);
Assert.AreEqual(ConnectionState.Disconnected, pusher.State);
Assert.IsTrue(doneEvent.WaitOne(TimeSpan.FromSeconds(5)));

Sample application

See the example app for details.

Configuration

The PusherOptions object

Constructing a Pusher client requires some options. These options are defined in a PusherOptions object:

Property Type Description
Authorizer IAuthorizer Required for authorizing private and presence channel subscriptions.
ClientTimeout TimeSpan The timeout period to wait for an asynchrounous operation to complete. The default value is 30 seconds.
Cluster String The Pusher host cluster name; for example, "eu". The default value is "mt1".
Encrypted Boolean Indicates whether the connection will be encrypted. The default value is false.
TraceLogger ITraceLogger Used for tracing diagnostic events. Should not be set in production code.

Application Key

The Pusher client constructor requires an application key which you can get from the app's API Access section in the Pusher Channels dashboard. It also takes a PusherOptions object as an input parameter.

Examples:

Construction of a public channel only subscriber

Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Cluster = Config.Cluster,
    Encrypted = true,
});

Construction of authorized private and presence channels subscriber

Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new HttpAuthorizer("http://localhost:8888/auth/Jane"),
    Cluster = Config.Cluster,
    Encrypted = true,
});

Specifying a client timeout

Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new HttpAuthorizer("http://localhost:8888/auth/Jane"),
    Cluster = Config.Cluster,
    Encrypted = true,
    ClientTimeout = TimeSpan.FromSeconds(20),
});

Connecting

Connection States

You can access the current connection state using Pusher.State and bind to state changes using Pusher.ConnectionStateChanged.

Possible States:

  • Uninitialized: Initial state; no event is emitted in this state.
  • Connecting: The channel client is attempting to connect.
  • Connected: The channel connection is open and authenticated with your app. Channel subscriptions can now be made.
  • Disconnecting: The channel client is attempting to disconnect.
  • Disconnected: The channel connection is disconnected and all subscriptions have stopped.
  • WaitingToReconnect: Once connected the channel client will automatically attempt to reconnect if there is a connection failure.

First call to Pusher.ConnectAsync() succeeds: Uninitialized -> Connecting -> Connected. Auto reconnect is enabled.

First call to Pusher.ConnectAsync() fails: Uninitialized -> Connecting. Auto reconnect is disabled. Pusher.ConnectAsync() will throw an exception and a Pusher.Error will be emitted.

Call to Pusher.DisconnectAsync() succeeds: Connected -> Disconnecting -> Disconnected. Auto reconnect is disabled.

Call to Pusher.DisconnectAsync() fails: Connected -> Disconnecting. Pusher.DisconnectAsync() will throw an exception.

Sample code:

pusher = new Pusher("YOUR_APP_KEY");
pusher.ConnectionStateChanged += StateChanged;
pusher.Error += ErrorHandler;

void StateChanged(object sender, ConnectionState state)
{
    Console.WriteLine("Connection state: " + state.ToString());
}

void ErrorHandler(object sender, PusherException error)
{
    Console.WriteLine("Pusher error: " + error.ToString());
}

try
{
    await pusher.ConnectAsync().ConfigureAwait(false);
    // pusher.State will be ConnectionState.Connected
}
catch(Exception error)
{
    // Handle error
}

Auto reconnect

After entering a state of Connected, auto reconnect is enabled. If the connection is dropped the channel client will attempt to re-establish the connection.

Here is a possible scenario played out after a connection failure.

  • Connection dropped
  • State transition: Connected -> Disconnected
  • State transition: Disconnected -> WaitingToReconnect
  • Pause for 1 second and attempt to reconnect
  • State transition: WaitingToReconnect -> Connecting
  • Connection attempt fails, network still down
  • State transition: Connecting -> Disconnected
  • State transition: Disconnected -> WaitingToReconnect
  • Pause for 2 seconds (max 10 seconds) and attempt to reconnect
  • State transition: WaitingToReconnect -> Connecting
  • Connection attempt succeeds
  • State transition: Connecting -> Connected

Disconnecting

After disconnecting, all subscriptions are stopped and no events will be received from the Pusher server host. Calling ConnectAsync will re-enable any subscriptions that were stopped when disconnecting. To permanently stop receiving events, unsubscribe from the channel.

// Disconnect
await pusher.DisconnectAsync().ConfigureAwait(false);
Assert.AreEqual(ConnectionState.Disconnected, pusher.State);

Connected and Disconnected delegates

The Pusher client has delegates for Connected and Disconnected events.

The Connected event is raised after connecting to the cluster host.

The Disconnected event is raised after disconnecting from the cluster host.

Sample code:

pusher = new Pusher("YOUR_APP_KEY", new PusherOptions(){
    Authorizer = new HttpAuthorizer("YOUR_ENDPOINT")
});

pusher.Connected += OnConnected;
pusher.Disconnected += OnDisconnected;

void OnConnected(object sender)
{
    Console.WriteLine("Connected: " + ((Pusher)sender).SocketID);
}

void OnDisconnected(object sender)
{
    Console.WriteLine("Disconnected: " + ((Pusher)sender).SocketID);
}

try
{
    await pusher.ConnectAsync().ConfigureAwait(false);
    // pusher.State will now be ConnectionState.Connected
}
catch(Exception error)
{
    // Handle error
}

do
{
    line = Console.ReadLine();
    if (line == "quit") break;
} while (line != null);

// Disconnect
await pusher.DisconnectAsync().ConfigureAwait(false);
// pusher.State will now be ConnectionState.Disconnected

Subscribing

Three types of channels are supported

  • Public channels: can be subscribed to by anyone who knows their name.
  • Private channels: are private in that you control access to who can subscribe to the channel.
  • Presence channels: are extensions to private channels and let you add user information on a subscription, and let other members of the channel know who is online.

There are two modes for creating channel subscriptions

  • Pre-connecting: setup all subscriptions first and then connect using Pusher.ConnectAsync. This is a purely asynchronous model. The subscriptions are created asynchronously after connecting. Error detection needs to be done via the error delegate Pusher.Error.
  • Post-connecting: setup all subscriptions after connecting using Pusher.ConnectAsync. This is a partly synchronous model. The subscriptions are created synchronously. If the method call fails; for example, the user is not authorized, an exception will be thrown. You will also receive an error via the delegate Pusher.Error.

Error handling

Regardless of the mode used, it is good to have error handling via the Pusher.Error delegate. For example, if you were to lose the network connection and the client attempts to auto reconnect, things happen asynchronously and the error handler is the only way to detect errors. Here is a sample error handler:

void ErrorHandler(object sender, PusherException error)
{
    if ((int)error.PusherCode < 5000)
    {
        // Error recevied from Pusher cluster, use PusherCode to filter.
    }
    else
    {
        if (error is ChannelUnauthorizedException unauthorizedAccess)
        {
            // Private and Presence channel failed authorization with Forbidden (403)
        }
        else if (error is ChannelAuthorizationFailureException httpError)
        {
            // Authorization endpoint returned an HTTP error other than Forbidden (403)
        }
        else if (error is OperationTimeoutException timeoutError)
        {
            // A client operation has timed-out. Governed by PusherOptions.ClientTimeout
        }
        else if (error is ChannelDecryptionException decryptionError)
        {
            // Failed to decrypt the data for a private encrypted channel
        }
        else
        {
            // Handle other errors
        }
    }
}

ErrorHandler will be referred to in the channel subscription examples.

Public channels

Setting up a public channel subscription before connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Subscribe
Channel channel = await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false);
Assert.AreEqual(false, channel.IsSubscribed);

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

Setting up a public channel subscription after connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

// Subscribe
try
{
    Channel channel = await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false);
    Assert.AreEqual(true, channel.IsSubscribed);
}
catch (Exception)
{
    // Handle error
}

Private channels

The name of a private channel needs to start with private-.

It's possible to subscribe to private channels that provide a mechanism for authenticating channel subscriptions. In order to do this you need to provide an IAuthorizer when creating the Pusher instance.

The library provides an HttpAuthorizer implementation of IAuthorizer which makes an HTTP POST request to an authenticating endpoint. However, you can implement your own authentication mechanism if required.

Setting up a private channel subscription before connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Subscribe
Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false);
Assert.AreEqual(false, channel.IsSubscribed);

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

Setting up a private channel subscription after connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

try
{
    // Subscribe
    Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false);
    Assert.AreEqual(true, channel.IsSubscribed);
}
catch (ChannelUnauthorizedException)
{
    // Handle client unauthorized error
}
catch (Exception)
{
    // Handle other errors
}

Private encrypted channels

Similar to Private channels, you can also subscribe to a private encrypted channel. This library now fully supports end-to-end encryption. This means that only you and your connected clients will be able to read your messages. Pusher cannot decrypt them.

Like the private channel, you must provide your own authentication endpoint, with your own encryption master key. There is a demonstration endpoint in the repo to look at using Nancy.

To get started you need to subscribe to your channel and bind to the events you are interested in; for example:

Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new HttpAuthorizer("http://localhost:8888/auth/joe"),
    Cluster = "eu",
    Encrypted = true,
});

// Listen for secret events
void GeneralListener(string eventName, PusherEvent eventData)
{
    if (eventName == "secret-event")
    {
        ChatMessage data = JsonConvert.DeserializeObject<ChatMessage>(eventData.Data);
        Console.WriteLine($"{Environment.NewLine}[{data.Name}] {data.Message}");
    }
}

// Handle decryption error
void DecryptionErrorHandler(object sender, PusherException error)
{
    if (error is ChannelDecryptionException exception)
    {
        string errorMsg = $"{Environment.NewLine}Decryption of message failed";
        errorMsg += $" for ('{exception.ChannelName}',";
        errorMsg += $" '{exception.EventName}', ";
        errorMsg += $" '{exception.SocketID}')";
        errorMsg += $" for reason:{Environment.NewLine}{error.Message}";
        Console.WriteLine(errorMsg);
    }
}

// Subcribe to private encrypted channel
pusher.Error += DecryptionErrorHandler;
pusher.BindAll(GeneralListener);
await pusher.SubscribeAsync("private-encrypted-channel").ConfigureAwait(false);

await pusher.ConnectAsync().ConfigureAwait(false);

See the example app for the Pusher client implementation.

Presence channels

The name of a presence channel needs to start with presence-.

The recommended way of subscribing to a presence channel is to use the SubscribePresenceAsync function, as opposed to the standard subscribe function. This function returns a strongly typed presence channel object with extra presence channel specific functions available to it, such as GetMember and GetMembers.

Setting up a presence channel subscription before connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Lists all current presence channel members
void ListMembers(GenericPresenceChannel<ChatMember> channel)
{
    Dictionary<string, ChatMember> members = channel.GetMembers();
    foreach (var member in members)
    {
        Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}");
    }
}

// MemberAdded event handler
void ChatMemberAdded(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has joined");
    ListMembers(sender as GenericPresenceChannel<ChatMember>);
}

// MemberRemoved event handler
void ChatMemberRemoved(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has left");
    ListMembers(sender as GenericPresenceChannel<ChatMember>);
}

// Subscribe
GenericPresenceChannel<ChatMember> memberChannel =
    await pusher.SubscribePresenceAsync<ChatMember>("presence-channel-1").ConfigureAwait(false);
memberChannel.MemberAdded += ChatMemberAdded;
memberChannel.MemberRemoved += ChatMemberRemoved;
Assert.AreEqual(false, memberChannel.IsSubscribed);

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

Setting up a presence channel subscription after connecting

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Lists all current presence channel members
void ListMembers(GenericPresenceChannel<ChatMember> channel)
{
    Dictionary<string, ChatMember> members = channel.GetMembers();
    foreach (var member in members)
    {
        Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}");
    }
}

// MemberAdded event handler
void ChatMemberAdded(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has joined");
    ListMembers(sender as GenericPresenceChannel<ChatMember>);
}

// MemberRemoved event handler
void ChatMemberRemoved(object sender, KeyValuePair<string, ChatMember> member)
{
    Trace.TraceInformation($"Member {member.Value.Name} has left");
    ListMembers(sender as GenericPresenceChannel<ChatMember>);
}

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

// Subscribe
try
{
    GenericPresenceChannel<ChatMember> memberChannel =
        await pusher.SubscribePresenceAsync<ChatMember>("presence-channel-1").ConfigureAwait(false);
    memberChannel.MemberAdded += ChatMemberAdded;
    memberChannel.MemberRemoved += ChatMemberRemoved;
    Assert.AreEqual(true, memberChannel.IsSubscribed);
}
catch (ChannelUnauthorizedException)
{
    // Handle client unauthorized error
}
catch (Exception)
{
    // Handle other errors
}

HttpAuthorizer

The implementation of the HttpAuthorizer class which provides the default implementation of an IAuthorizer has been modified to support the setting of an authentication header.

Here is an example of how to set the bearer token in an authentication header:

var authorizer = new HttpAuthorizer("https:/some.authorizer.com/auth")
{
     AuthenticationHeader = new AuthenticationHeaderValue("Authorization", "Bearer noo6xaeN3cohYoozai4ar8doang7ai1elaeTh1di"),
};
var authToken = await authorizer.Authorize("private-test", "1234.9876");

If you require setting other headers you can override the PreAuthorize method on the HttpAuthorizer class.

public override void PreAuthorize(HttpClient httpClient)
{
    base.PreAuthorize(httpClient);

    // Add headers or other settings to the httpClient before authorizing.
}

Subscribed delegate

The Subscribed delegate is invoked when a channel is subscribed to. There are two different ways to specify a Subscribed event handler:

  • Add an event handler using the Pusher.Subscribed delegate property. This event handler can be used to detect all channel subscriptions.
  • Provide an event handler as an input parameter to the SubscribeAsync or SubscribePresenceAsync methods. This event handler is channel specific.

Detect all channel subscribed events using Pusher.Subscribed

// Lists all current presence channel members
void ListMembers(GenericPresenceChannel<ChatMember> channel)
{
    Dictionary<string, ChatMember> members = channel.GetMembers();
    foreach (var member in members)
    {
        Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}");
    }
}

// Subscribed event handler
void SubscribedHandler(object sender, Channel channel)
{
    if (channel is GenericPresenceChannel<ChatMember> presenceChannel)
    {
        ListMembers(presenceChannel);
    }
    else if (channel.Name == "private-chat-channel-1")
    {
        // Trigger event
        channel.Trigger("client-chat-event", new ChatMessage
        {
            Name = "Joe",
            Message = "Hello from Joe!",
        });
    }
}

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Add subcribed event handler
pusher.Subscribed += SubscribedHandler;

// Create subscriptions
await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false);
await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false);
await pusher.SubscribePresenceAsync<ChatMember>("presence-channel-1").ConfigureAwait(false);

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

Detect a subscribed event on a channel

// Lists all current presence channel members
void ListMembers(GenericPresenceChannel<ChatMember> channel)
{
    Dictionary<string, ChatMember> members = channel.GetMembers();
    foreach (var member in members)
    {
        Trace.TraceInformation($"Id: {member.Key}, Name: {member.Value.Name}");
    }
}

// Presence channel subscribed event handler
void PresenceChannelSubscribed(object sender)
{
    ListMembers(sender as GenericPresenceChannel<ChatMember>);
}

// Private channel subscribed event handler
void PrivateChannelSubscribed(object sender)
{
    // Trigger event
    ((Channel)sender).Trigger("client-chat-event", new ChatMessage
    {
        Name = "Joe",
        Message = "Hello from Joe!",
    });
}

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Create subscriptions
await pusher.SubscribeAsync("public-channel-1").ConfigureAwait(false);
await pusher.SubscribeAsync("private-chat-channel-1", PrivateChannelSubscribed)
    .ConfigureAwait(false);
await pusher.SubscribePresenceAsync<ChatMember>("presence-channel-1", PresenceChannelSubscribed)
    .ConfigureAwait(false);

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

Unsubscribe

You can use UnsubscribeAsync and UnsubscribeAllAsync to remove subscriptions.

// Remove a channel subscription
await pusher.UnsubscribeAsync("public-channel-1").ConfigureAwait(false);

// Remove all channel subscriptions
await pusher.UnsubscribeAllAsync().ConfigureAwait(false);

Subscription Count Handler

Add this handler to recieve subscription count events. Read more about it here

void PusherCountEventHandler(object sender, string data) {
    var dataAsObj = JsonConvert.DeserializeObject<SubscriptionCountData>(data);
    Console.WriteLine(dataAsObj.subscriptionCount);
}

pusher.CountHandler += PusherCountEventHandler;

Binding to events

Events can be bound to at two levels; per-channel or globally.

The binding samples make use of the following classes

class ChatMember
{
    public string Name { get; set; }
}

class ChatMessage : ChatMember
{
    public string Message { get; set; }
}

Per-channel

These are bound to a specific channel, and mean that you can reuse event names in different parts of your client application.

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Channel event listener
void ChannelListener(PusherEvent eventData)
{
    ChatMessage data = JsonConvert.DeserializeObject<ChatMessage>(eventData.Data);
    Trace.TraceInformation($"Message from '{data.Name}': {data.Message}");
}

// Subscribe
Channel channel = await pusher.SubscribeAsync("private-chat-channel-1")
    .ConfigureAwait(false);

// Bind event listener to channel
channel.Bind("client-chat-event", ChannelListener);

// Unbind event listener from channel
channel.Unbind("client-chat-event", ChannelListener);

// Unbind all "client-chat-event" event listeners from the channel
channel.Unbind("client-chat-event");

// Unbind all event listeners from the channel
channel.UnbindAll();

Globally

You can attach behavior to these events regardless of the channel the event is broadcast to.

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Global event listener
void GlobalListener(string eventName, PusherEvent eventData)
{
    if (eventName == "client-chat-event")
    {
        ChatMessage data = JsonConvert.DeserializeObject<ChatMessage>(eventData.Data);
        Trace.TraceInformation($"Message from '{data.Name}': {data.Message}");
    }
}

// Bind global event listener
pusher.BindAll(GlobalListener);

// Unbind global event listener
pusher.Unbind(GlobalListener);

// Unbind all event listeners associated with the Pusher client
pusher.UnbindAll();

Triggering events

Once a private or presence subscription has been authorized (see authenticating users) and the subscription has succeeded, it is possible to trigger events on those channels.

// Create client
Pusher pusher = new Pusher(Config.AppKey, new PusherOptions
{
    Authorizer = new FakeAuthoriser(),
    Cluster = Config.Cluster,
});
pusher.Error += ErrorHandler;

// Connect
await pusher.ConnectAsync().ConfigureAwait(false);

// Subscribe
Channel channel = await pusher.SubscribeAsync("private-chat-channel-1").ConfigureAwait(false);

// Trigger event
channel.Trigger("client-chat-event", new ChatMessage
{
    Name = "Joe",
    Message = "Hello from Joe!",
});

Events triggered by clients are called client events. Because they are being triggered from a client which may not be trusted there are a number of enforced rules when using them. Some of these rules include:

  • Event names must have a client- prefix
  • Rate limits
  • You can only trigger an event when the subscription has succeeded

For full details see the client events documentation.

Developer notes

The Pusher application settings are now loaded from a JSON config file stored in the root of the source tree and named AppConfig.test.json. Make a copy of ./AppConfig.sample.json and name it AppConfig.test.json. Modify the contents of AppConfig.test.json with your test application settings. All tests should pass. The AuthHost and ExampleApplication should also run without any start-up errors.

Testing

The majority of the tests are concurrency tests and the more the number of CPU(s) used the better. All tests should pass. However, some of the error code test paths fail intermittently when running on 2 CPU(s) - default build server configuration. With this in mind it is good to test on a 2 CPU configuration. A test settings file has been added to the root (CPU.count.2.runsettings) and you can specify it when running the tests via the menu option [Test]/[Configure Run Settings].

Also, a random latency is induced when authorizing a subscription. This is to weed out some of the concurrency issues. This adds to the time it takes to run all the tests. If you are running the tests often, you can speed things up by disabling the latency induction. Set the property EnableAuthorizationLatency to false in AppConfig.test.json.

Some of the tests have trace statements using System.Diagnostics.Trace. One way to view them is to debug a test and open the Output\Debug window.

Code signing key generation

To generate a new signing key, open a PowerShell command console and execute the command

./StrongName/GeneratePusherKey.ps1

Copy the public key file PusherClient.public.snk to the source root folder.

Take the base 64 encoded string and add it to the environment secret named CI_CODE_SIGN_KEY. This is used by publish.yml. Once this step is done remove all traces of the private signing key file.

Also copy the PublicKey text and apply it to the code file ./PusherClient/Properties/AssemblyInfo.Signed.cs; for example

[assembly: InternalsVisibleTo("PusherClient.Tests, PublicKey=00240...8c1")]
[assembly: InternalsVisibleTo("PusherClient.Tests.Utilities, PublicKey=00240...8c1")]

Migrating from version 1 to version 2

You are encouraged to move to the Pusher Client SDK version 2. This major release includes a number of bug fixes and performance improvements. See the changelog for more information.

The following sections describe the changes in detail and describes how to update your code to the new version 2.x. If you run into problems you can always contact [email protected].

Changed in the Pusher class

Previously the ConnectAsync returned a ConnectionState enum value after an async await. This is no longer the case; it returns void now. After the async await the state is always Connected if the call succeeds. If the call fails an exception will be thrown.

Removed from the Pusher class

Removed the public property ConcurrentDictionary<string, Channel> Channels. Use the method GetAllChannels() instead.

Removed the public static property TraceSource Trace. Use PusherOptions.TraceLogger instead.

Removed from the Channel class

Removed the public event delegate SubscriptionEventHandler Subscribed. Use the optional input parameter SubscriptionEventHandler subscribedEventHandler on Pusher.SubscribeAsync and Pusher.SubscribePresenceAsync instead. Alternatively, use Pusher.Subscribed.

Removed from the GenericPresenceChannel class

Removed the public property ConcurrentDictionary<string, T> Members. Use GetMembers() instead.

Removed from the ConnectionState enum

Six states remain simplifying the state change model:

  • Uninitialized
  • Connecting - Unimplemented state change in SDK version 1
  • Connected - Unimplemented state change in SDK version 1
  • Disconnecting
  • Disconnected
  • WaitingToReconnect

These states have been removed:

  • Initialized
  • NotConnected
  • AlreadyConnected
  • ConnectionFailed
  • DisconnectionFailed

Changed in the GenericPresenceChannel class

The signature of the MemberRemoved delegate has changed from MemberRemovedEventHandler MemberRemoved to MemberRemovedEventHandler<T> MemberRemoved.

Added to the Pusher class

An optional parameter SubscriptionEventHandler subscribedEventHandler has been added to the SubscribeAsync and SubscribePresenceAsync<T> methods.

/// <summary>
/// Fires when a channel becomes subscribed.
/// </summary>
public event SubscribedEventHandler Subscribed;
/// <summary>
/// Gets a channel.
/// </summary>
/// <param name="channelName">The name of the channel to get.</param>
/// <returns>The <see cref="Channel"/> if it exists; otherwise <c>null</c>.</returns>
public Channel GetChannel(string channelName)
{
    // ...
}
/// <summary>
/// Get all current channels.
/// </summary>
/// <returns>A list of the current channels.</returns>
public IList<Channel> GetAllChannels()
{
    // ...
}
/// <summary>
/// Removes a channel subscription.
/// </summary>
/// <param name="channelName">The name of the channel to unsubscribe.</param>
/// <returns>An awaitable task to use with async operations.</returns>
public async Task UnsubscribeAsync(string channelName)
{
    // ...
}
/// <summary>
/// Removes all channel subscriptions.
/// </summary>
/// <returns>An awaitable task to use with async operations.</returns>
public async Task UnsubscribeAllAsync()
{
    // ...
}

Added to the GenericPresenceChannel class

/// <summary>
/// Gets a member using the member's user ID.
/// </summary>
/// <param name="userId">The member's user ID.</param>
/// <returns>Retruns the member if found; otherwise returns null.</returns>
public T GetMember(string userId)
{
    // ...
}
/// <summary>
/// Gets the current list of members as a <see cref="Dictionary{TKey, TValue}"/>
/// where the TKey is the user ID and TValue is the member detail.
/// </summary>
/// <returns>Returns a <see cref="Dictionary{TKey, TValue}"/> containing the current members.</returns>
public Dictionary<string, T> GetMembers()
{
    // ...
}

Added to the ErrorCodes enum

Error codes less than 5000 remain the same. These are the error codes you can get from the Pusher server.

Error codes 5000 and above have been added for Client SDK detected errors. Almost all of these codes can be associated with a new exception class that derives from PusherException.

License

This code is free to use under the terms of the MIT license.

More Repositories

1

pusher-js

Pusher Javascript library
JavaScript
1,970
star
2

atom-pair

An Atom package that allows for epic pair programming
JavaScript
1,454
star
3

pusher-http-php

PHP library for interacting with the Pusher Channels HTTP API
PHP
1,355
star
4

pusher-http-ruby

Ruby library for Pusher Channels HTTP API
Ruby
659
star
5

libPusher

An Objective-C interface to Pusher Channels
C
409
star
6

pusher-http-laravel

[DEPRECATED] A Pusher Channels bridge for Laravel
PHP
405
star
7

pusher-http-python

Pusher Channels HTTP API library for Python
Python
368
star
8

k8s-spot-rescheduler

Tries to move K8s Pods from on-demand to spot instances
Go
311
star
9

pusher-websocket-java

Pusher Channels client library for Java targeting general Java and Android
Java
302
star
10

pusher-websocket-swift

Pusher Channels websocket library for Swift
Swift
267
star
11

build-a-slack-clone-with-react-and-pusher-chatkit

In this tutorial, you'll learn how to build a chat app with React, complete with typing indicators, online status, and more.
JavaScript
235
star
12

pusher-angular

Pusher Angular Library | owner=@leesio
JavaScript
233
star
13

pusher-http-go

Pusher Channels HTTP API library for Go
Go
196
star
14

k8s-spot-termination-handler

Monitors AWS for spot termination notices when run on spot instances and shuts down gracefully
Makefile
118
star
15

NWWebSocket

A WebSocket client written in Swift, using the Network framework from Apple.
Swift
112
star
16

go-interface-fuzzer

Automate the boilerplate of fuzz testing Go interfaces | owner: @willsewell
Go
110
star
17

pusher-http-dotnet

.NET library for interacting with the Pusher HTTP API
C#
109
star
18

k8s-auth-example

Example Kubernetes Authentication helper. Performs OIDC login and configures Kubectl appropriately.
Go
108
star
19

faros

Faros is a CRD based GitOps controller
Go
100
star
20

backbone-todo-app

JavaScript
92
star
21

chatkit-client-js

JavaScript client SDK for Pusher Chatkit
JavaScript
89
star
22

quack

In-Cluster templating for Kubernetes manifests
Go
70
star
23

pusher-channels-flutter

Pusher Channels client library for Flutter targeting IOS, Android, and WEB
Dart
67
star
24

websockets-from-scratch-tutorial

Tutorial that shows how to implement a websocket server using Ruby's built-in libs
Ruby
60
star
25

backpusher

JavaScript
54
star
26

push-notifications-php

Pusher Beams PHP Server SDK
PHP
54
star
27

chatkit-android

Android client SDK for Pusher Chatkit
Kotlin
54
star
28

pusher-websocket-react-native

React Native official Pusher SDK
TypeScript
53
star
29

django-pusherable

Real time notification when an object view is accessed via Pusher
Python
52
star
30

notify

Ruby
51
star
31

cli

A CLI for Pusher (beta)
Go
50
star
32

k8s-spot-price-monitor

Monitors the spot prices of instances in a Kubernetes cluster and exposes them as prometheus metrics
Python
44
star
33

chatkit-command-line-chat

A CLI chat, built with Chatkit
JavaScript
41
star
34

pusher-http-java

Java client to interact with the Pusher HTTP API
Java
40
star
35

chatkit-swift

Swift SDK for Pusher Chatkit
Swift
40
star
36

electron-desktop-chat

A desktop chat built with React, React Desktop and Electron
JavaScript
39
star
37

push-notifications-web

Beams Browser notifications
JavaScript
38
star
38

crank

Process slow restarter
Go
37
star
39

pusher-websocket-android

Library built on top of pusher-websocket-java for Android. Want Push Notifications? Check out Pusher Beams!
Java
35
star
40

chameleon

A collection of front-end UI components used across Pusher ✨
CSS
35
star
41

chatkit-server-php

PHP SDK for Pusher Chatkit
PHP
35
star
42

cide

Isolated test runner with Docker
Ruby
33
star
43

push-notifications-swift

Swift SDK for the Pusher Beams product:
Swift
33
star
44

pusher-phonegap-android

JavaScript
30
star
45

push-notifications-python

Pusher Beams Python Server SDK
Python
30
star
46

pusher-websocket-unity

Pusher Channels Unity Client Library
C#
27
star
47

hacktoberfest

24
star
48

laravel-chat

PHP
22
star
49

push-notifications-android

Android SDK for Pusher Beams
Kotlin
21
star
50

push-notifications-node

Pusher Beams Node.js Server SDK
JavaScript
20
star
51

pusher-test-iOS

iOS app for developers to test connections to Pusher
Objective-C
19
star
52

push-notifications-ruby

Pusher Beams Ruby Server SDK
Ruby
19
star
53

chatkit-server-node

Node.js SDK for Pusher Chatkit
TypeScript
16
star
54

rack-headers_filter

Remove untrusted headers from Rack requests | owner=@zimbatm
Ruby
15
star
55

pusher-test-android

Test and diagnostic app for Android, based on pusher-java-client
Java
14
star
56

pusher-realtime-tfl-cameras

Realtime TfL Traffic Camera API, powered by Pusher
JavaScript
14
star
57

buddha

Buddha command execution and health checking | owner: @willsewell
Go
14
star
58

chatkit-server-go

Chatkit server SDK for Golang
Go
13
star
59

pusher-channels-auth-example

A simple server exposing a pusher auth endpoint
JavaScript
13
star
60

pusher-platform-js

Pusher Platform client library for browsers and react native
TypeScript
13
star
61

stronghold

[DEPRECATED] A configuration service | owner: @willsewell
Haskell
12
star
62

pusher-twilio-example

CSS
12
star
63

prom-rule-reloader

Watches configmaps for prometheus rules and keeps prometheus in-sync
Go
12
star
64

sample-chatroom-ios-chatkit

How to make an iOS Chatroom app using Swift and Chatkit
PHP
11
star
65

electron-desktop-starter-template

JavaScript
11
star
66

chatkit-server-ruby

Ruby server SDK for Chatkit
Ruby
11
star
67

realtime-visitor-tracker

Realtime location aware visitor tracker for a web site or application
PHP
11
star
68

push-notifications-server-java

Pusher Beams Java Server SDK
Kotlin
10
star
69

android-slack-clone

Android chat application, built with Chatkit
Kotlin
10
star
70

filtrand

JavaScript
10
star
71

vault

Front-end pattern library
Ruby
9
star
72

push-notifications-go

Pusher Beams Go Server SDK
Go
9
star
73

pusher-platform-android

Pusher Platform SDK for Android
Kotlin
9
star
74

git-store

Go git abstraction for use in Kubernetes Controllers
Go
8
star
75

pusher-platform-swift

Swift SDK for Pusher platform products
Swift
8
star
76

realtime_survey_complete

JavaScript
8
star
77

docs

The all new Pusher docs, powered by @11ty and @vercel
CSS
8
star
78

push-notifications-server-swift

Pusher Beams Swift Server SDK
Swift
8
star
79

pusher-python-rest

Python client to interact with the Pusher REST API. DEPRECATED in favour of https://github.com/pusher/pusher-http-python
Python
8
star
80

real-time-progress-bar-tutorial

Used inthe realtime progress bar tutorial blog post - http://blog.pusher.com
JavaScript
7
star
81

pusher-channels-chunking-example

HTML
7
star
82

pusher-http-swift

Swift library for interacting with the Pusher Channels HTTP API
Swift
7
star
83

feeds-client-js

JS client for Pusher Feeds
JavaScript
6
star
84

pusher-test

Simple website which allows manual testing of pusher-js versions
JavaScript
6
star
85

java-websocket

A fork of https://github.com/TooTallNate/Java-WebSocket | owner=@zmarkan
HTML
6
star
86

bridge-troll

A Troll that ensures files don't change
Go
5
star
87

navarchos

Node replacing controller
Go
5
star
88

realtime-notifications-tutorial

Create realtime notifications in minutes, not days =)
4
star
89

pusher-socket-protocol

Protocol for pusher sockets
HTML
4
star
90

icanhazissues

Github issues kanban
JavaScript
4
star
91

textsync-server-node

[DEPRECATED] A node.js library to simplify token generation for TextSync authorization endpoints.
TypeScript
4
star
92

pusher_tutorial_realtimeresults

JavaScript
3
star
93

pusher-js-diagnostics

JavaScript
3
star
94

react-rest-api-tutorial

Accompanying tutorial for consuming RESTful APIs in React
CSS
3
star
95

testing

Configuration for Pusher's Open Source Prow instance
Go
3
star
96

feeds-server-node

The server Node SDK for Pusher Feeds
JavaScript
3
star
97

spacegame_example

Simple example of a space game using node.js and Pusher
JavaScript
3
star
98

chatkit-quickstart-swift

A project to get started with Chatkit.
Swift
2
star
99

pusher-whos-in

Ruby
2
star
100

chatkit-android-public-demo

This will hold the demo app for chatkit android. Owner: @daniellevass
Kotlin
2
star