The following example demonstrates how to set up event handlers for the events exposed by the XmppClient class.

Hooking up to events

  1. The XmppClient class exposes a variety of events that can be subscribed to in order to be notified of the receipt of new chat messages, status changes of a chat contact, incoming authorization requests, etc. The following piece of example code shows how to hook up to the Message event in order to be notified of the receipt of new chat-messages:

    CopyC#
    using S22.Xmpp.Client;
    using System;
    
    namespace ConsoleApplication53 {
        class Program {
            static void Main(string[] args) {
                string hostname = "jabber.se";
                string username = "myusername";
                string password = "mypassword";
    
                using (XmppClient client = new XmppClient(hostname, username, password)) {
                    // Setup any event handlers before connecting.
                    client.Message += OnNewMessage;
                    // Connect and authenticate with the server.
                    client.Connect();
    
                    Console.WriteLine("Type 'quit' to exit.");
                    while (Console.ReadLine() != "quit");
                }
            }
    
            /// <summary>
            /// Invoked whenever a new chat-message has been received.
            /// </summary>
            static void OnNewMessage(object sender, MessageEventArgs e) {
                Console.WriteLine("Message from <" + e.Jid + ">: " + e.Message.Body);
            }
        }
    }

  2. Whenever a chat-message is sent to myusername@jabber.se, the OnNewMessage method will be invoked. The MessageEventArgs parameter contains information about the sender of the message as well its content.

Robust Programming

Event handlers are invoked sequentially on a separate thread.

You should not call blocking methods from within event handlers and you must not directly update UI controls from within an event handler. Rather, you should call the Invoke method of the respective UI control to have the control updated on the thread that owns the control's underlying window handle.

See Also