Skip to content

Instantly share code, notes, and snippets.

@matsadler
Created January 17, 2010 22:56
Show Gist options
  • Save matsadler/279643 to your computer and use it in GitHub Desktop.
Save matsadler/279643 to your computer and use it in GitHub Desktop.
# http://dnssd.rubyforge.org/dnssd/
# http://xmpp.org/extensions/xep-0174.html
# http://home.gna.org/xmpp4r/
require 'rubygems'
require 'dnssd'
require 'xmpp4r'
# An example of how to send messages to iChat with the bonjour chat protocol
# using ruby.
# This makes it easier to see where things go wrong
Thread.abort_on_exception = true
name = "foo@bar" # name@location
type = "_presence._tcp" # the mDNS service type
domain = "local" # the subnet we're on, almost always 'local'
port = 5000 # the port other people can contact us on
txt_record = DNSSD::TextRecord.new(
"txtvers" => "1", # required, always 1
"port.p2pj" => port, # for back compatibility
"status" => "avail", # avail, away, or dnd
"1st" => name.split(/@/).first.capitalize) # The name other people see
# Announce our availability
# ! method runs in the current thread, without the ! a new thread is created,
# but not joined, so we'd fall through and exit.
DNSSD.register!(name, type, domain, port, txt_record) do |registered|
# Find some other users
browser = DNSSD::Service.new
browser.browse(type) do |browsed|
# skip any results that tell us they have more details coming
next if browsed.flags.to_i & DNSSD::Flags::MoreComing > 0
# skip if the user is us
next if browsed.fullname == registered.fullname
# stop when we've found someone
browser.stop
# discover the host and port to comunicate with this user on
resolver = DNSSD::Service.new
resolver.resolve(browsed.name, browsed.type, browsed.domain) do |resolved|
next if resolved.flags.to_i & DNSSD::Flags::MoreComing > 0
# stop as soon as we have resolved the user
resolver.stop
# the protocol is pretty much just XMPP/jabber
jid = Jabber::JID.new(name)
client = Jabber::Client.new(jid)
# for some reason we have to wait a little before we connect
sleep 0.5
# connect to the host/port we got from resolving the user
client.connect(resolved.target, resolved.port)
# construct and send our message
message = Jabber::Message.new(resolved.name, "hi")
client.send(message)
# and we're done
client.close
exit
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment