Class: Votifier::Server
- Inherits:
-
Object
- Object
- Votifier::Server
- Defined in:
- lib/votifier/server.rb
Defined Under Namespace
Classes: Error
Instance Attribute Summary collapse
-
#private_key ⇒ Object
readonly
Returns the value of attribute private_key.
Instance Method Summary collapse
- #decrypt(encrypted_string) ⇒ Object
- #handle_connection(client) ⇒ Object
- #init_private_key(private_key_file) ⇒ Object
-
#initialize(opts) ⇒ Server
constructor
A new instance of Server.
- #listen ⇒ Object
- #parse_content(content) ⇒ Object
Constructor Details
#initialize(opts) ⇒ Server
Returns a new instance of Server.
7 8 9 10 |
# File 'lib/votifier/server.rb', line 7 def initialize(opts) raise ':private_key options is required' unless opts.key?(:private_key) init_private_key(opts[:private_key]) end |
Instance Attribute Details
#private_key ⇒ Object (readonly)
Returns the value of attribute private_key.
5 6 7 |
# File 'lib/votifier/server.rb', line 5 def private_key @private_key end |
Instance Method Details
#decrypt(encrypted_string) ⇒ Object
51 52 53 54 |
# File 'lib/votifier/server.rb', line 51 def decrypt(encrypted_string) string = private_key.private_decrypt(encrypted_string) string end |
#handle_connection(client) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/votifier/server.rb', line 25 def handle_connection(client) lines = "" while line = client.gets lines += line end begin vote_info = parse_content(lines) vote = Vote.from_array(vote_info) puts vote.to_h client.close # Disconnect from the client rescue => e puts e.inspect puts e.backtrace end end |
#init_private_key(private_key_file) ⇒ Object
12 13 14 |
# File 'lib/votifier/server.rb', line 12 def init_private_key(private_key_file) @private_key = Votifer::Key.from_key_file(private_key_file) end |
#listen ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/votifier/server.rb', line 16 def listen server = TCPServer.open(8193) # Socket to listen on port loop { # Servers run forever Thread.start(server.accept) do |client| # Wait for a client to connect handle_connection(client) end } end |
#parse_content(content) ⇒ Object
41 42 43 44 45 46 47 48 49 |
# File 'lib/votifier/server.rb', line 41 def parse_content(content) raise Error::InvalidVotePacket, "Must be 256 bytes: is #{content.bytesize}" unless content.bytesize == 256 vote_info_string = decrypt(content) raise Error::InvalidVotePacket, 'Must contains newline characters' unless vote_info_string.match(/\n/) vote_info = vote_info_string.split("\n") raise Error::InvalidVotePacket, 'Must contain 5 elements or more' unless vote_info.size >= 5 raise Error::InvalidVotePacket, 'Invalid opcode: must be VOTE' unless vote_info[0] == "VOTE" vote_info end |