Module: UrlTracker::SocketCommunication

Included in:
Client, Server
Defined in:
lib/url_tracker/socket_communication.rb

Overview

Implements communication via Unix sockets.

Constant Summary collapse

InvalidSocketError =
Class.new(StandardError)
MAX_MESSAGE_LENGTH =

Messages received cannot be longer than 1024 bytes

1024
MAX_CONN_QUEUE =

Max connections to be queued before accept

10

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#path=(value) ⇒ Object (writeonly)

path to the socket file



7
8
9
# File 'lib/url_tracker/socket_communication.rb', line 7

def path=(value)
  @path = value
end

Instance Method Details

#bind(path) ⇒ Object

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.



30
31
32
33
34
35
36
37
# 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_connectionObject



58
59
60
61
# 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) ⇒ Object

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.



20
21
22
23
24
25
# 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_messageObject

Waits for a message. Blocks until it is received.



53
54
55
56
# 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_connectionObject

Waits for a connection in the binded socket



40
41
42
# File 'lib/url_tracker/socket_communication.rb', line 40

def wait_for_connection
  @current_client = @socket.accept.first
end

#write(message) ⇒ Object

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



47
48
49
50
# File 'lib/url_tracker/socket_communication.rb', line 47

def write(message)
  socket = (defined? @current_client) ? @current_client : @socket
  socket.send(message, 0)
end