Class: UUID::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/uuid.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initializeServer

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



409
410
411
# File 'lib/uuid.rb', line 409

def initialize()
  @generator = UUID.new
end

Instance Method Details

#bind(address) ⇒ Object

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



431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/uuid.rb', line 431

def bind(address)
  return address unless String === address
  if address[0] == ?/
    if File.exist?(address)
      raise ArgumentError, "#{address} is not a socket" unless File.socket?(address)
      File.unlink(address)
    end
    sock = UNIXServer.new(address)
    File.chmod 0666, address
  elsif address =~ /^(\d+\.\d+\.\d+\.\d+):(\d+)$/
    sock = TCPServer.new($1, $2.to_i)
  else
    raise ArgumentError, "Don't know how to bind #{address}"
  end
  sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) if defined?(TCP_NODELAY)
  sock
end

#listen(address) ⇒ Object

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)



418
419
420
421
422
423
424
425
426
427
# File 'lib/uuid.rb', line 418

def listen(address)
  sock = bind(address)
  while client = sock.accept
    Thread.start(client) do |socket|
      while socket.read 1
        socket.write @generator.generate
      end
    end
  end
end