Openfire Logo

XmppDotNet: A Minimal Working Example (in C# / .NET)

Introduction

This document provides a minimal working example of a client implementation using the XmppDotNet library, making it connect to a running Openfire server.

Topics that are covered in this document:

Background

XmppDotNet is a cross platform XMPP SDK for the full .NET Framework, .NET Core and Mono

This guide describes how to use XmppDotNet to connect to Openfire. It provides nothing more than a minimal working example, intended as a stepping stone to for client developers that get started with a new project.

Preparations

In this example, a client connection will be made against a running Openfire server. For ease of configuration, the 'demoboot' setup of Openfire is used.

The 'demoboot' setup of Openfire allows one to start a fresh installation of Openfire into a certain provisioned state, without running any of the setup steps. When running in 'demoboot' mode:

To start Openfire in 'demoboot' mode, you can invoke the Openfire executable using the -demoboot argument, as shown below.

Starting Openfire in 'demoboot' mode.
$ ./bin/openfire.sh -demoboot

Code

To start the project, create a file named Program.cs in an empty directory, and copy in the code below.

Example Program file
// setup XmppClient with some properties
var xmppClient = new XmppClient(
        conf =>
        {
            conf
                .UseSocketTransport(new StaticNameResolver(new Uri("tcp://localhost:5222")))
                .WithCertificateValidator(new AlwaysAcceptCertificateValidator());
        }
    )
    {
        Jid = "john@example.org",
        Password = "secret"
    };

// subscribe to the Binded session state
xmppClient
    .StateChanged
    .Where(s => s == SessionState.Binded)
    .Subscribe(async v =>
    {
        // request roster (contact list).
        // This is optional, but most chat clients do this on startup
        var roster = await xmppClient.RequestRosterAsync();

        // send our online presence to the server
        await xmppClient.SendPresenceAsync(Show.Chat, "free for chat");

        // send a chat message to user2
        await xmppClient.SendChatMessageAsync("jane@example.org", "This is a test");
    });

// connect so the server
await xmppClient.ConnectAsync();

// wait for a key press
Console.ReadLine();

// Close connection again
await xmppClient.DisconnectAsync();

Use any other XMPP client to log in with the user 'jane', then run this code. You will see that it will send a message to Jane!

Note that this example disables important security features. You should not use this for anything important!

Further Reading

Please use the links below to find more information.