Class: SimpleIPC::Socket
- Inherits:
-
Object
- Object
- SimpleIPC::Socket
- Defined in:
- lib/simple_ipc.rb
Overview
Wrapper class exposing the same API for UNIXSocket and UDPSocket classes.
Instance Method Summary (collapse)
-
- (Object) close
Closes the socket and removes the socket file if it exists.
-
- (Object) connect
Opens the connection.
-
- (Socket) initialize(args = {})
constructor
A new instance of Socket.
-
- (Object) listen
Listens for incoming messages, i.e.
-
- (Object) print(string)
Sends a String through the socket.
-
- (String) recv_nonblock(bytes)
Receives a message of length bytes in non-blocking way.
-
- (String) recvfrom(bytes)
Receives a message of length bytes.
Constructor Details
- (Socket) initialize(args = {})
A new instance of Socket
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/simple_ipc.rb', line 34 def initialize(args = {}) @cfg = { :port => 5000, :host => LOCALHOST, :kind => :unix, :force => true } @cfg.merge! args case @cfg[:kind] when :unix @socket_file = "/tmp/#{$0}.sok" @socket = nil when :udp @socket = UDPSocket.new else raise ArgumentError, "Either :unix or :udp allowed" end @open = false end |
Instance Method Details
- (Object) close
Closes the socket and removes the socket file if it exists.
109 110 111 112 113 |
# File 'lib/simple_ipc.rb', line 109 def close @socket.close @open = false FileUtils::rm(@socket_file) if @socket_file end |
- (Object) connect
Opens the connection. Only has to be called once before sending messages. Only used for client sockets.
56 57 58 59 60 61 62 63 64 65 |
# File 'lib/simple_ipc.rb', line 56 def connect return false if @open case @cfg[:kind] when :unix @socket = UNIXSocket.open(@socket_file) when :udp @socket.connect(@cfg[:host], @cfg[:port]) end @open = true end |
- (Object) listen
Listens for incoming messages, i.e. becomes a server. If +@cfg+ is true, it also silently removes any existing stale socket file, otherwise stops.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/simple_ipc.rb', line 78 def listen case @cfg[:kind] when :unix @socket = UNIXServer.open(@socket_file).accept when :udp @socket.bind(BROADCAST, @cfg[:port]) end rescue Errno::EADDRINUSE if @cfg[:force] then FileUtils::rm(@socket_file) retry else raise Errno::EADDRINUSE, $! end end |
- (Object) print(string)
Sends a String through the socket.
69 70 71 |
# File 'lib/simple_ipc.rb', line 69 def print(string) @socket.print(string) end |
- (String) recv_nonblock(bytes)
Receives a message of length bytes in non-blocking way.
104 105 106 |
# File 'lib/simple_ipc.rb', line 104 def recv_nonblock(bytes) @socket.recv_nonblock(bytes) end |
- (String) recvfrom(bytes)
Receives a message of length bytes.
97 98 99 |
# File 'lib/simple_ipc.rb', line 97 def recvfrom(bytes) @socket.recvfrom(bytes) end |