Class: Netsoul::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/netsoul/client.rb

Constant Summary collapse

SOCKET_READ_TIMEOUT =
12 * 60
SOCKET_WRITE_TIMEOUT =
1 * 60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
# File 'lib/netsoul/client.rb', line 12

def initialize(*args)
  opts = args.last.is_a?(Hash) ? args.last : {}
  @config = Config.new(opts)
  @started = false
end

Instance Attribute Details

#startedObject (readonly)

Returns the value of attribute started.



8
9
10
# File 'lib/netsoul/client.rb', line 8

def started
  @started
end

Instance Method Details

#connectObject



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/netsoul/client.rb', line 41

def connect
  @socket = TCPSocket.new(@config.server_host, @config.server_port)
  raise Netsoul::SocketError, 'Could not open a socket. Connection is unavailable.' unless @socket
  _cmd, _socket_num, md5_hash, client_ip, client_port, _server_timestamp = get.split

  @config.build_user_connection_info md5_hash: md5_hash, client_ip: client_ip, client_port: client_port

  auth_ag
  auth_method
  auth_status

  @started = true
end

#disconnectObject



55
56
57
58
59
60
# File 'lib/netsoul/client.rb', line 55

def disconnect
  send(Message.ns_exit)
  close
ensure
  @started = false
end

#getObject



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/netsoul/client.rb', line 70

def get
  sock, = IO.select([@socket], nil, nil, SOCKET_READ_TIMEOUT)
  s = sock.first
  raise Netsoul::SocketError, 'Timeout or raise on read socket' unless s
  res = s.gets.chomp
  if !res.empty?
    res
  else
    'nothing' # Send some string and permit IO.select to thrown exception if something goes wrong.
  end
end

#send(str) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/netsoul/client.rb', line 62

def send(str)
  _, sock = IO.select(nil, [@socket], nil, SOCKET_WRITE_TIMEOUT)
  s = sock.first
  raise Netsoul::SocketError, 'Timeout or raise on write socket' unless s
  s.puts str
  s.flush
end