Class: ServerWrapper

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

Overview

The wrapper for TCPServer.

Instance Method Summary collapse

Constructor Details

#initialize(port = 2000) ⇒ ServerWrapper

Returns a new instance of ServerWrapper.



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/accu-net.rb', line 34

def initialize(port=2000)
  @port = TCPServer.open port
  catch :close do
    loop do
      @server = @port.accept
      @password,@mode = "password",:double
      yield self,@server if block_given?
      @server.close
    end
  end
  @port.close
end

Instance Method Details

#closeObject

Throws :close to end the serving process.



110
111
112
# File 'lib/accu-net.rb', line 110

def close
  throw :close
end

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

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

Yields:

  • (msg)


49
50
51
52
# File 'lib/accu-net.rb', line 49

def listen()
  msg = @server.gets.chomp
  yield msg
end

#listen_codeObject

Listens for a network code.



65
66
67
68
69
70
71
72
73
# File 'lib/accu-net.rb', line 65

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_linesObject

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



56
57
58
59
60
61
62
# File 'lib/accu-net.rb', line 56

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

#send(text) ⇒ Object

Sends a plaintext message.



76
77
78
# File 'lib/accu-net.rb', line 76

def send(text)
  @server.puts text
end

#send_code(code) ⇒ Object

Sends a code.



99
100
101
# File 'lib/accu-net.rb', line 99

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

#send_encrypted(lines) ⇒ Object

Send over an encrypted multiline message.



91
92
93
94
95
96
# File 'lib/accu-net.rb', line 91

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.



82
83
84
85
86
87
88
# File 'lib/accu-net.rb', line 82

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.



104
105
106
107
# File 'lib/accu-net.rb', line 104

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