module UrlTracker::SocketCommunication

Implements communication via Unix sockets.

Constants

InvalidSocketError
MAX_CONN_QUEUE

Max connections to be queued before accept

MAX_MESSAGE_LENGTH

Messages received cannot be longer than 1024 bytes

Attributes

path[W]

Public Instance Methods

bind(path) click to toggle source

Binds the given path, creating a Unix socket. As with connect, you cannot use this method if already called connect before. After this method is called, the socket will be waiting for connections.

# File lib/url_tracker/socket_communication.rb, line 30
def bind(path)
  raise_socket_error_if { defined? @socket }
  @socket_file = path
  @socket = Socket.new(:UNIX, :SOCK_STREAM, 0)
  @socket.bind addrinfo_for(@socket_file)
  @socket.listen(MAX_CONN_QUEUE)
  true
end
close_connection() click to toggle source
# File lib/url_tracker/socket_communication.rb, line 58
def close_connection
  defined?(@socket) && !@socket.closed? && @socket.close
  File.unlink(@socket_file) if defined?(@socket_file) && File.exists?(@socket_file)
end
connect(path) click to toggle source

Connects to the Unix socket. Returns true if the connection was successful. Otherwise an exception is thrown. This method cannot be called if bind was already called; neither can you call bind if you call this method.

# File lib/url_tracker/socket_communication.rb, line 20
def connect(path)
  raise_socket_error_if { defined? @socket }
  @socket = Socket.new(:UNIX, :SOCK_STREAM, 0)
  @socket.connect addrinfo_for(path)
  true
end
next_message() click to toggle source

Waits for a message. Blocks until it is received.

# File lib/url_tracker/socket_communication.rb, line 53
def next_message
  socket = (defined? @current_client) ? @current_client : @socket
  socket.recvfrom(MAX_MESSAGE_LENGTH).first
end
wait_for_connection() click to toggle source

Waits for a connection in the binded socket

# File lib/url_tracker/socket_communication.rb, line 40
def wait_for_connection
  @current_client = @socket.accept.first
end
write(message) click to toggle source

Writes to the socket, returning the number of bytes sent. This method can only be called before connect or wait_for_connection, otherwise you will get an exception

# File lib/url_tracker/socket_communication.rb, line 47
def write(message)
  socket = (defined? @current_client) ? @current_client : @socket
  socket.send(message, 0)
end

Private Instance Methods

addrinfo_for(path) click to toggle source
# File lib/url_tracker/socket_communication.rb, line 69
def addrinfo_for(path)
  Addrinfo.unix(path)
end
raise_socket_error_if(&block) click to toggle source
# File lib/url_tracker/socket_communication.rb, line 65
def raise_socket_error_if(&block)
  raise InvalidSocketError if block.call
end