C#C# V4 SDK 4.11.0.0

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

SDK getting startedSample app quickstart
  1. PubNub account

  2. Download the SDK

  3. Send messages

  • n/a


Sign in or create an account to create an app on the PubNub Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use Nuget

To integrate PubNub into your project using the Nuget package manager:


<!-- For .Net 3.5/4.0/4.5/4.61 -->
https://www.nuget.org/packages/Pubnub/4.11.0.0

<!-- For Xamarin.Android, Xamarin.iOS and .Net Core/.Net Standard -->
https://www.nuget.org/packages/PubnubPCL/4.11.0.0

<!--For Universal Windows  -->
https://www.nuget.org/packages/PubnubUWP/4.11.0.0

Get the source code

Configure PubNub


In the IDE of your choice, create a new App class and add the following code. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the PubNub Dashboard.

 using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.Uuid = "myUniqueUUID";

Pubnub pubnub = new Pubnub(pnConfiguration);

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

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the following code to configure your app such that when it receives an event of type PNConnectedCategory, it calls the Publish() function.


pubnub.AddListener(new SubscribeCallbackExt(
    delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
    {
        if (pubMsg != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNMessageResult");
            Debug.WriteLine("In Example, SubscribeCallback messsage channel = " + pubMsg.Channel);
            Debug.WriteLine("In Example, SubscribeCallback messsage channelGroup = " + pubMsg.Subscription);
            Debug.WriteLine("In Example, SubscribeCallback messsage publishTimetoken = " + pubMsg.Timetoken);
            Debug.WriteLine("In Example, SubscribeCallback messsage publisher = " + pubMsg.Publisher);
            string jsonString = pubMsg.Message.ToString();
            Dictionary<string, string> msg = pubnub.JsonPluggableLibrary.DeserializeToObject<Dictionary<string,string>>(jsonString);
            Debug.WriteLine("msg: " + msg["msg"]);
        }
    },
    delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt)
    {
        if (presenceEvnt != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNPresenceEventResult");
            Debug.WriteLine(presenceEvnt.Channel + " " + presenceEvnt.Occupancy + " " + presenceEvnt.Event);
        }
    },
    delegate (Pubnub pnObj, PNStatus pnStatus)
    {
        if (pnStatus.Category == PNStatusCategory.PNConnectedCategory) {
        pubnub.Publish()
        .Channel("my_channel")
        .Message(message)
        .Execute(new PNPublishResultExt((publishResult, publishStatus) => {
            if (!publishStatus.Error) {
                Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
            } else {
                Debug.WriteLine(publishStatus.Error);
                Debug.WriteLine(publishStatus.ErrorData.Information);
            }
        }));
        }
    }
)

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

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered when the status listener you created in the previous step receives the PNConnectedCategory event.

To subscribe, you send a subscribe() call. It is best to define the message before you introduce the listeners and send the subscribe call, so make sure to place the relevant code in the appropriate places within the App class.


Dictionary<string, string> message = new Dictionary<string, string>();
    message.Add("msg", "Hello world!");

pubnub.Subscribe<string>()
        .Channels(new string[]{ 
            "my_channel" 
        }).Execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Your App file should now look similar to the one below:

using PubnubApi;

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.Uuid = "myUniqueUUID";

Dictionary<string, string> message = new Dictionary<string, string>();
message.Add("msg", "Hello world");

Pubnub pubnub = new Pubnub(pnConfiguration);

pubnub.AddListener(new SubscribeCallbackExt(
    delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
    {
        if (pubMsg != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNMessageResult");
            Debug.WriteLine("In Example, SubscribeCallback messsage channel = " + pubMsg.Channel);
            Debug.WriteLine("In Example, SubscribeCallback messsage channelGroup = " + pubMsg.Subscription);
            Debug.WriteLine("In Example, SubscribeCallback messsage publishTimetoken = " + pubMsg.Timetoken);
            Debug.WriteLine("In Example, SubscribeCallback messsage publisher = " + pubMsg.Publisher);
            string jsonString = pubMsg.Message.ToString();
            Dictionary<string, string> msg = pubnub.JsonPluggableLibrary.DeserializeToObject<Dictionary<string,string>>(jsonString);
            Debug.WriteLine("msg: " + msg["msg"]);
        }
    },
    delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt)
    {
        if (presenceEvnt != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNPresenceEventResult");
            Debug.WriteLine(presenceEvnt.Channel + " " + presenceEvnt.Occupancy + " " + presenceEvnt.Event);
        }
    },
    delegate (Pubnub pnObj, PNStatus pnStatus)
    {
        if (pnStatus.Category == PNStatusCategory.PNConnectedCategory) {
        pubnub.Publish()
        .Channel("my_channel")
        .Message(message)
        .Execute(new PNPublishResultExt((publishResult, publishStatus) => {
            if (!publishStatus.Error) {
                Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
            } else {
                Debug.WriteLine(publishStatus.Error);
                Debug.WriteLine(publishStatus.ErrorData.Information);
            }
        }));
        }
    }
)

pubnub.Subscribe<string>()
    .Channels(new string[]{ 
        "my_channel" 
    }).Execute();

Now, run your app to see if you did everything correctly. You should see "Hello world" printed in the console.

Congratulations! You've just subscribed to a channel and sent your first message.

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the status, message, and presence event listeners
  • subscribes to a channel
  • publishes a message

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

PNConfiguration pnConfiguration = new PNConfiguration();
pnConfiguration.SubscribeKey = "mySubscribeKey";
pnConfiguration.PublishKey = "myPublishKey";
pnConfiguration.Uuid = "myUniqueUUID";

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added three listeners to the app: message, presence, and status. The message listener listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message. This is why you see "Hello world" displayed in the console.

The presence listener reacts to events connected to presence. In this example, when a new subscriber joins a channel, the information about the channel and its occupancy is printed out to the console.

The most noteworthy of listeners in this example is the status listener that triggers the publishing of the "Hello world" message.


pubnub.AddListener(new SubscribeCallbackExt(
    delegate (Pubnub pnObj, PNMessageResult<object> pubMsg)
    {
        if (pubMsg != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNMessageResult");
            Debug.WriteLine("In Example, SubscribeCallback messsage channel = " + pubMsg.Channel);
            Debug.WriteLine("In Example, SubscribeCallback messsage channelGroup = " + pubMsg.Subscription);
            Debug.WriteLine("In Example, SubscribeCallback messsage publishTimetoken = " + pubMsg.Timetoken);
            Debug.WriteLine("In Example, SubscribeCallback messsage publisher = " + pubMsg.Publisher);
            string jsonString = pubMsg.Message.ToString();
            Dictionary<string, string> msg = pubnub.JsonPluggableLibrary.DeserializeToObject<Dictionary<string,string>>(jsonString);
            Debug.WriteLine("msg: " + msg["msg"]);
        }
    },
    delegate (Pubnub pnObj, PNPresenceEventResult presenceEvnt)
    {
        if (presenceEvnt != null) {
            Debug.WriteLine("In Example, SubscribeCallback received PNPresenceEventResult");
            Debug.WriteLine(presenceEvnt.Channel + " " + presenceEvnt.Occupancy + " " + presenceEvnt.Event);
        }
    },
    delegate (Pubnub pnObj, PNStatus pnStatus)
    {
        if (pnStatus.Category == PNStatusCategory.PNConnectedCategory) {
        pubnub.Publish()
        .Channel("my_channel")
        .Message(message)
        .Execute(new PNPublishResultExt((publishResult, publishStatus) => {
            if (!publishStatus.Error) {
                Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
            } else {
                Debug.WriteLine(publishStatus.Error);
                Debug.WriteLine(publishStatus.ErrorData.Information);
            }
        }));
        }
    }
)

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

PubNub uses the Publish/Subscribe model for realtime communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named my_channel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When your app successfully connects to a channel, it calls the Publish() method, which sends the "Hello world" message.

Dictionary<string, string> message = new Dictionary<string, string>();
    message.Add("msg", "Hello world");

delegate (Pubnub pnObj, PNStatus pnStatus)
    {
        if (pnStatus.Category == PNStatusCategory.PNConnectedCategory) {
        pubnub.Publish()
        .Channel("my_channel")
        .Message(message)
        .Execute(new PNPublishResultExt((publishResult, publishStatus) => {
            if (!publishStatus.Error) {
                Debug.WriteLine(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow, publishResult.Timetoken));
            } else {
                Debug.WriteLine(publishStatus.Error);
                Debug.WriteLine(publishStatus.ErrorData.Information);
            }
        }));
        }
    }

You can subscribe to more than one channel with a single subscribe call but in this example, you subscribe to a single channel:

pubnub.Subscribe<string>()
        .Channels(new string[]{ 
            "my_channel" 
        }).Execute();

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

You have just learned how to use the C# SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation, which covers PubNub API in more detail.