class UNIX::Socket
Public Class Methods
new(path, &block)
click to toggle source
Creates a new Unix socket connection.
# File lib/unix/socket.rb, line 6 def initialize(path, &block) @path = path @addr = socket_addr(@path) @on_read = block connect end
Public Instance Methods
close()
click to toggle source
Closes the socket connection.
# File lib/unix/socket.rb, line 26 def close @handle.closeFile @handle = nil end
dealloc()
click to toggle source
Cleans up the socket.
Calls superclass method
# File lib/unix/socket.rb, line 32 def dealloc notification_center.removeObserver(self) close super end
read()
click to toggle source
Reads available data on the communication channel and returns it as an NSData object. If no data is available, the method blocks.
# File lib/unix/socket.rb, line 15 def read data = @handle.availableData return data end
write(data)
click to toggle source
Writes the given data to the socket.
# File lib/unix/socket.rb, line 21 def write(data) @handle.writeData(data) end
Private Instance Methods
connect()
click to toggle source
Connects to the socket. When the socket is read from, the on_read callback will be called.
# File lib/unix/socket.rb, line 56 def connect @sockfd = socket(AF_UNIX, SOCK_STREAM, 0) connect(@sockfd, @addr, @addr.value.sa_len) @handle = NSFileHandle.alloc.initWithFileDescriptor(@sockfd) if @on_read notification_center.addObserver(self, selector: "msg_received:", name: NSFileHandleReadCompletionNotification, object: @handle) @handle.readInBackgroundAndNotify end end
msg_received(notification)
click to toggle source
Called when an asynchronous message is received on the socket. Passes the data on the communication channel to the block provided.
# File lib/unix/socket.rb, line 71 def msg_received(notification) data = notification.userInfo.objectForKey(NSFileHandleNotificationDataItem) if data.length > 0 NSLog("msg_received") @on_read.call(data) end @handle.readInBackgroundAndNotify end
notification_center()
click to toggle source
Returns the default notification center.
# File lib/unix/socket.rb, line 81 def notification_center NSNotificationCenter.defaultCenter end
socket_addr(path)
click to toggle source
Returns a pointer to a Sockaddr corresponding to the given path.
# File lib/unix/socket.rb, line 41 def socket_addr(path) addr = Sockaddr_un.new addr.sun_family = AF_UNIX path.each_char.each_with_index do |c, i| addr.sun_path[i] = c end addr.sun_len = Type.sizeof(Sockaddr_un.type) addr_ptr = Pointer.new(Sockaddr_un.type, 1) addr_ptr[0] = addr addr_ptr.cast!(Sockaddr.type) return addr_ptr end