Connect and send message

This basic example shows how to connect to a server and send a siple chat message to another user. The steps required are the following:

  • Create XmppClient and set username, password and XMPP domain properties
  • call connect to create the connection, authenticate etc…
  • Request the contact list from the server (optional)
  • Send our own presence to the server
  • Send a chat message from the logged in user1 to user2 on the same server which is example.com

Example

// setup XmppClient with some properties
var xmppClient = new XmppClient(
        conf =>
        {
            conf.UseSocketTransport();
            //conf.UseWebSocketTransport();
            conf.AutoReconnect = true;

            // when your server dow not support SRV records or
            // XEP-0156 Discovering Alternative XMPP Connection Methods
            // then you need to supply host and port for the connection as well.
            // See docs => Host disconvery
        }
    )
    {
        Jid = "user1@server.com",
        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("user2@exmaple.com", "This is a test");
    });

// connect so the server
await xmppClient.ConnectAsync();
 
// wait for a key press
Console.ReadLine();

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