Class: ClientWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/accu-net.rb

Overview

The wrapper for TCPClient.

Instance Method Summary collapse

Constructor Details

#initialize(port = 2000, ip = "127.0.0.1") {|_self, @client| ... } ⇒ ClientWrapper

Returns a new instance of ClientWrapper.

Yields:

  • (_self, @client)

Yield Parameters:

  • _self (ClientWrapper)

    the object that the method was called on



133
134
135
136
137
138
# File 'lib/accu-net.rb', line 133

def initialize(port=2000,ip="127.0.0.1")
  @client = TCPSocket.open(ip, port)
  @password,@mode = "password",:double
  yield self,@client if block_given?
  @client.close
end

Instance Method Details

#listen {|msg| ... } ⇒ Object

Listens for a generic network communication and yields to a passed block (if any).

Yields:

  • (msg)


142
143
144
145
146
# File 'lib/accu-net.rb', line 142

def listen()
  msg = @client.gets.chomp
  yield msg if block_given?
  return msg
end

#listen_codeObject

Listens for a network code.



159
160
161
162
163
164
165
166
167
# File 'lib/accu-net.rb', line 159

def listen_code()
  listen { |msg|
    if msg.slice(0..1) == "C:" then
      return msg.slice(2..msg.length).to_i
    else
      return msg.slice(0..1)
    end
  }
end

#listen_encryptedObject

Listen for an encrypted connection.



170
171
172
173
174
175
176
177
# File 'lib/accu-net.rb', line 170

def listen_encrypted()
  if listen_code == 3 then
    password,source = EncryptDecrypt.decrypt(@password,((listen_lines).join),@mode)
    return source
  else
    raise "Sent code was not 3!"
  end
end

#listen_linesObject

Listens for multiple lines, appends them together and stops at END.



150
151
152
153
154
155
156
# File 'lib/accu-net.rb', line 150

def listen_lines()
  lines = []
  while line = @client.gets.chomp and line != "END" do
    lines << line
  end
  lines
end

#send(text) ⇒ Object

Sends a plaintext message.



180
181
182
# File 'lib/accu-net.rb', line 180

def send(text)
  @client.puts text
end

#send_code(code) ⇒ Object

Sends a code.



203
204
205
# File 'lib/accu-net.rb', line 203

def send_code(code)
  send("C:#{code}")
end

#send_encrypted(lines) ⇒ Object

Send over an encrypted multiline message.



195
196
197
198
199
200
# File 'lib/accu-net.rb', line 195

def send_encrypted(lines)
  secret,text = EncryptDecrypt.encrypt(@password,lines,@mode)
  send_code(3)
  send(text)
  send("END")
end

#send_lines(lines) ⇒ Object

Sends multiple lines and appends END to end the send.



186
187
188
189
190
191
192
# File 'lib/accu-net.rb', line 186

def send_lines(lines)
  array = lines.split("\n")
  array.each do |line|
    send(line)
  end
  send("END")
end

#set_password(string) ⇒ Object

Set encryption password.



208
209
210
211
# File 'lib/accu-net.rb', line 208

def set_password(string)
  warn "Argument 1 is not a string!  Continuing anyway." if not string.is_a? String
  @password = string.to_s
end