class Nastika::Base
It serves as a layer of abstraction between us and Ruby's socket library.
Attributes
connected[RW]
host[RW]
payload[RW]
port[RW]
protocol[RW]
sock[RW]
Public Class Methods
new(protocol=nil, host=nil, port=nil, payload=nil)
click to toggle source
Initializes the Nastika::Base
object Params:
protocol
-
The protocol to use.
host
-
The host to connect to (can be nil)
port
-
The port on the host (can be nil)
payload
-
The payload to send to the host (can be nil)
# File lib/nastika/base.rb, line 26 def initialize(protocol=nil, host=nil, port=nil, payload=nil) if protocol.nil? raise ArgumentError, "We need atleast a protocol." end self.host = host self.port = port self.payload = payload self.protocol = protocol self.connected = false case protocol when Nastika::Constants::TCP self.sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) when Nastika::Constants::UDP self.sock = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM, 0) else raise ArgumentError, "#{protocol} is not supported. Try all-lowercase." end end
Public Instance Methods
connect()
click to toggle source
Connects to the host
# File lib/nastika/base.rb, line 80 def connect unless host.nil? & port.nil? begin self.sock.connect(Socket.sockaddr_in(port, host)) self.connected = true rescue => e self.connected = false raise e end else raise ArgumentError, "host and port cannot be nil." end end
get(bytes=Nastika::Constants::DEFAULT_BYTES, timeout=Nastika::Constants::DEFAULT_WAIT_TIME)
click to toggle source
Gets data from the host. Params:
bytes
-
the amount of bytes to recieve (can be nil) (Default: 1024)
timeout
-
the amount of time to wait for data (in secs) (can be nil) (Default: 10)
# File lib/nastika/base.rb, line 69 def get(bytes=Nastika::Constants::DEFAULT_BYTES, timeout=Nastika::Constants::DEFAULT_WAIT_TIME) Timeout.timeout(timeout) do begin recvd = self.sock.recv(bytes) rescue => e raise e end end end
quit()
click to toggle source
closes the connection
# File lib/nastika/base.rb, line 95 def quit self.sock.close if self.connected end
send(pd=nil)
click to toggle source
Sends data to host. If payload is empty, uses the passed argument and sets it as the payload. Params:
pd
-
the payload to send (can be nil if payload was set beforehand.)
# File lib/nastika/base.rb, line 49 def send(pd=nil) if self.payload.nil? self.payload = pd to_send = self.payload elsif self.payload to_send = self.payload else raise ArgumentError, "cannot send nil payload." end begin self.sock.write(to_send) rescue => e puts e end end