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
Create new server. Nothing interesting happens until you call listen.
# File lib/uuid.rb, line 408 def initialize() @generator = UUID.new end
Public Instance Methods
Returns UNIXServer or TCPServer from address. Returns argument if not a string, so can pass through (see listen).
# File lib/uuid.rb, line 430 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
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, line 417 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