Programmierung Jabber components
I could not really find an easy example how to get started with Jabber components (using xmpp4r), so this I will cover the absolute basics here.
You will need a Jabber server to connect your component to. I suggest to install ejabberd locally. Also needed is xmpp4r, which can be installed through rubygems (e.g. using sudo gem install xmpp4r
). Feel free to use your favourite package manager to install it, if packaged.
The following snippet is used to configure ejabberd to listen for your component. After altering the configuration, do not forget to restart ejabberd. DNS seems to be important for elang-stuff, so make sure the host you use (e.g. localhost) can be resolved properly.
{5348, ejabberd_service, [
{access, all},
{shaper_rule, fast},
{ip, {127, 0, 0, 1}},
{host, "mycomponent.localhost",
[{password, "secret"}]
}
]},
Take a look at the sample configfile and use a predefined, commented service configuration, so you won’t have to fiddle with erlang-stuff.
Now you can create this small file, name it mycomponent.rb
and use the following content:
require 'xmpp4r'
class MyComponent < Jabber::Component
def initialize config
super config['jid']
# connect to the main server
connect config['server'], config['port']
# authenticate
auth config['password']
add_message_callback do |message|
Thread.new do
handle_message message
end
end
# stop this thread
Thread.stop
end
# handles incoming messages
def handle_message message
puts "received message from #{message.from}: #{message.body}"
end
end
# configuration
config = {
'jid' => 'mycomponent.localhost',
'server' => 'localhost',
'port' => 5348,
'password' => 'secret'
}
# instantiate, connect and auth
mycomponent = MyComponent.new config
Using this kind of Hash as configuration makes it very easy to use YAML to store your configuration in a file. If ruby can’t find xmpp4r, you might have to require 'rubygems'
before, if you installed xmpp4r via rubygems.
Now you can run your component and send messages to mycomponent.localhost. The handle_message
will print any messages received.