C# API & SDK Docs 7.3.8

In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNub

PubNub

PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including:

:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your C# application, covering environments like .NET Framework, .NET Core, Xamarin, etc.

The core PubNub concepts and API usage are consistent across different C# platforms.

SDK packages

PubNub provides different NuGet packages optimized for various .NET environments:

  • Pubnub: For .NET Framework 4.6.1+
  • PubnubPCL: For .NET Standard 2.0+ (includes .NET Core, Xamarin)
  • PubnubUWP: For Universal Windows Platform Choose the package that best suits your target platform during installation.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of C#
  • A C# development environment (Visual Studio, Visual Studio Code, Rider)
  • .NET Framework 4.6.1+ or .NET Core 2.0+ installed
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

  • Sign in or create an account on the PubNub Admin Portal.
  • Create a new app (or use an existing one).
  • Find your publish

    Publish Key

    A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
    and subscribe

    Subscribe Key

    A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.
    keys in the app's dashboard (use the demo keys provided in the examples for now if you just want to test).

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

Install the SDK

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

To integrate PubNub into your project using the NuGet package manager, choose the command relevant to your project type:

.NET CLI

# For .NET Core / .NET Standard / Xamarin
dotnet add package PubnubPCL

# For .NET Framework 4.6.1+
dotnet add package Pubnub

# For Universal Windows Platform (UWP)
dotnet add package PubnubUWP

Package Manager Console in Visual Studio

# For .NET Core / .NET Standard / Xamarin
Install-Package PubnubPCL

# For .NET Framework 4.6.1+
Install-Package Pubnub

# For Universal Windows Platform (UWP)
Install-Package PubnubUWP

You can also get the source code directly from GitHub.

Steps

Initialize PubNub

You'll need to initialize the PubNub client with your unique keys to establish a connection to the PubNub network. This is the minimum configuration required to send and receive messages with PubNub in your application.

In a standard C# application (like a console app or backend service), you typically initialize PubNub at the application's entry point or within a dedicated service class.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal

using System;
using System.Collections.Generic;
using System.Diagnostics; // Or your preferred logging framework
using System.Threading.Tasks;
using PubnubApi;

public class App
{
private static Pubnub pubnub;

public static async Task Main(string[] args)
{
// Configure PubNub
PNConfiguration pnConfiguration = new PNConfiguration(new UserId("myUniqueUserId"))
{
show all 49 lines

This code configures and initializes PubNub within the Main method of a console application.

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners allow your application to react to incoming messages and other PubNub events in real-time.

Add the SetupListeners method to your App class. In a console or backend application, listeners might log messages or trigger other business logic.

// Add this method inside the App class

static void SetupListeners()
{
var listener = new SubscribeCallbackExt(
// Handle Message Events
(pn, messageEvent) =>
{
Console.WriteLine($"Message Received: Channel={messageEvent.Channel}, Message={messageEvent.Message}");

var messageData = messageEvent.Message as Dictionary<string, object>;
if (messageData != null && messageData.ContainsKey("text"))
{
Console.WriteLine($"Parsed Text: {messageData["text"]}");
}
show all 45 lines

For more information, refer to the Listeners section of the SDK documentation.

Create a subscription

Subscribing tells PubNub that you want to receive messages published to specific channels.

Add the SubscribeToChannel method to your App class. We call this in Main() after setting up listeners.

// Add this method inside the App class

static void SubscribeToChannel(string channelName)
{
pubnub.Subscribe<string>() // Use object if message type is unknown/mixed
.Channels(new string[] { channelName })
// .ChannelGroups(new string[] { "my_group" })
.WithPresence()
.Execute();

Console.WriteLine($"Subscribed to channel: {channelName}");
}

Publish messages

Publishing sends messages to a specific channel for all subscribed clients to receive.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

Add the PublishMessageAsync method to your App class. We call this from Main() in our example. Using async/await is common in C# for I/O operations.

// Add this method inside the App class

static async Task PublishMessageAsync(string channelName, Dictionary<string, object> message)
{
try
{
var result = await pubnub.Publish() // Using async/await
.Channel(channelName)
.Message(message)
// .Meta(new Dictionary<string, string> { { "sender", "ConsoleApp" } }) // Optional metadata
// .ShouldStore(true) // Optional: Store message in history
.ExecuteAsync();

if (!result.Status.Error)
{
show all 27 lines

Run the app

Now it's time to see your application in action!

  1. Build your C# project (e.g., dotnet build).
  2. Run the compiled application (e.g., dotnet run or execute the .exe file).
  3. Observe the console output. You should see messages indicating initialization, connection, subscription, and the results of any publish operations.
  4. If you publish a message, you should see the "Message Received" output shortly after in the same console (since it's subscribed to the channel it's publishing to).
  5. Run a second instance of the application to see messages published by one instance appearing in the other.
  6. Press any key in the console window to exit the application cleanly.

Here's the expected output in the console:

PubNub Initialized!
PubNub Listeners Set Up.
Subscribed to channel: my_channel
Message Published! Timetoken: 16788864001234567 // Timetoken will vary
Connected to PubNub on channel(s): my_channel
Message Received: Channel=my_channel, Message={"text":"Hello from C# Console!"}
Parsed Text: Hello from C# Console!
Press any key to exit...

Complete example

Here's the complete working example that puts everything together.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using PubnubApi;

namespace PubNubGetStarted
{
public class Program
{
private static Pubnub pubnub;

public static async Task Main(string[] args)
{
// Configure PubNub
show all 130 lines

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct (ensure they match the ones in your PubNub Admin Portal if not using "demo").
  • Check for firewall restrictions that might block outbound connections to PubNub servers.
Message not received
  • Double-check that both publisher and subscriber are using the exact same channel name.
  • Verify the message was published successfully (check for publish error logs).
  • Ensure the listener callback logic correctly handles incoming messages and logs them.
  • Confirm the Subscribe call was executed after listeners were added.
Build/Compile errors
  • Ensure you've installed the correct PubNub NuGet package.
  • Check that all necessary using PubnubApi; statements are present.
  • Verify you're targeting a compatible .NET Framework/Standard version.

Next steps

Great job! 🎉 You've successfully created your first PubNub C# application. Here are some exciting things you can explore next:

  • Learn about the Unity Chat SDK for ready-to-use chat features.
  • Implement user Presence to show who's online.
  • Add typing indicators and read receipts.
Last updated on