Class: Netsoul::Client

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

Constant Summary collapse

SOCKET_READ_TIMEOUT =
12 * 60
SOCKET_WRITE_TIMEOUT =
1 * 60

Constants included from Logging

Logging::PREFIX

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Client

Returns a new instance of Client.



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

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.



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

def started
  @started
end

Instance Method Details

#closeObject



85
86
87
88
89
# File 'lib/netsoul/client.rb', line 85

def close
  @socket.close if @socket
ensure
  @started = false
end

#connectObject



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

def connect
  @socket = TCPSocket.new(@config.server_host, @config.server_port)
  raise Netsoul::SocketError, 'Could not open a socket. Connection is unavailable.'.freeze 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



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

def disconnect
  send(Message.ns_exit)
ensure
  close
end

#getObject



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/netsoul/client.rb', line 73

def get
  sock, = IO.select([@socket], nil, nil, SOCKET_READ_TIMEOUT)
  raise Netsoul::SocketError, 'Timeout or raise on read socket'.freeze if sock.nil? || sock.empty?
  res = sock.first.gets
  if res
    log :info, "[get ] #{res.chomp}"
    res
  else
    'nothing'.freeze # 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
69
70
71
# File 'lib/netsoul/client.rb', line 62

def send(str)
  _, sock = IO.select(nil, [@socket], nil, SOCKET_WRITE_TIMEOUT)
  raise Netsoul::SocketError, 'Timeout or raise on write socket'.freeze if sock.nil? || sock.empty?
  s = sock.first
  if s
    s.puts str
    s.flush
  end
  log :info, "[send] #{str.chomp}"
end