class UUID::Server

With UUID server you don't have to worry about multiple processes synchronizing over the state file, calling next_sequence when forking a process and other things you're probably not worried about (because statistically they're very unlikely to break your code).

But if you are worried about and thought to yourself, “what would a simple UUID server look like?”, here's the answer. The protocol is dead simple: client sends a byte, server responds with a UUID. Can use TCP or domain sockets.

Public Class Methods

new() click to toggle source

Create new server. Nothing interesting happens until you call listen.

    # File lib/uuid.rb
400 def initialize()
401   @generator = UUID.new
402 end

Public Instance Methods

bind(address) click to toggle source

Returns UNIXServer or TCPServer from address. Returns argument if not a string, so can pass through (see listen).

    # File lib/uuid.rb
422 def bind(address)
423   return address unless String === address
424   if address[0] == ?/
425     if File.exist?(address)
426       raise ArgumentError, "#{address} is not a socket" unless File.socket?(address)
427       File.unlink(address)
428     end
429     sock = UNIXServer.new(address)
430     File.chmod 0666, address
431   elsif address =~ /^(\d+\.\d+\.\d+\.\d+):(\d+)$/
432     sock = TCPServer.new($1, $2.to_i)
433   else
434     raise ArgumentError, "Don't know how to bind #{address}"
435   end
436   sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) if defined?(TCP_NODELAY)
437   sock
438 end
listen(address) click to toggle source

Start the server listening on the specific address. Blocks and never returns. Address can be:

  • A Socket object

  • UNIX domain socket name (e.g. /var/run/uuid.sock, must start with /)

  • IP address, colon, port (e.g. localhost:1337)

    # File lib/uuid.rb
409 def listen(address)
410   sock = bind(address)
411   while client = sock.accept
412     Thread.start(client) do |socket|
413       while socket.read 1
414         socket.write @generator.generate
415       end
416     end
417   end
418 end