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
409 def initialize()
410   @generator = UUID.new
411 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
431 def bind(address)
432   return address unless String === address
433   if address[0] == ?/
434     if File.exist?(address)
435       raise ArgumentError, "#{address} is not a socket" unless File.socket?(address)
436       File.unlink(address)
437     end
438     sock = UNIXServer.new(address)
439     File.chmod 0666, address
440   elsif address =~ /^(\d+\.\d+\.\d+\.\d+):(\d+)$/
441     sock = TCPServer.new($1, $2.to_i)
442   else
443     raise ArgumentError, "Don't know how to bind #{address}"
444   end
445   sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) if defined?(TCP_NODELAY)
446   sock
447 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
418 def listen(address)
419   sock = bind(address)
420   while client = sock.accept
421     Thread.start(client) do |socket|
422       while socket.read 1
423         socket.write @generator.generate
424       end
425     end
426   end
427 end