-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver_accept_thread_and_gets_timeout.rb
75 lines (68 loc) · 1.93 KB
/
server_accept_thread_and_gets_timeout.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require 'socket'
require 'timeout'
class BasicServer
COMMANDS = [
"GET",
"SET",
]
def initialize
@clients = []
@data_store = {}
server = TCPServer.new 2000
puts "Server started at: #{ Time.now }"
Thread.new do
loop do
new_client = server.accept
@clients << new_client
end
end
loop do
@clients.each do |client|
begin
Timeout::timeout(0.1) do
client_command_with_args = client.gets
if client_command_with_args.nil?
puts "Found a client at eof, closing and removing"
@clients.delete(client)
elsif client_command_with_args.strip.empty?
puts "Empty request received from #{ client }"
else
response = handle_client_command(client_command_with_args.strip)
client.puts response
end
end
rescue Timeout::Error
puts "Did not receive anything from client after 0.1s, moving on"
next
rescue Errno::ECONNRESET
@clients.delete(client)
end
end
end
end
private
def handle_client_command(client_command_with_args)
command_parts = client_command_with_args.split
command = command_parts[0]
args = command_parts[1..-1]
if COMMANDS.include?(command)
if command == "GET"
if args.length != 1
"(error) ERR wrong number of arguments for '#{ command }' command"
else
@data_store.fetch(args[0], "(nil)")
end
elsif command == "SET"
if args.length != 2
"(error) ERR wrong number of arguments for '#{ command }' command"
else
@data_store[args[0]] = args[1]
'OK'
end
end
else
formatted_args = args.map { |arg| "`#{ arg }`," }.join(" ")
"(error) ERR unknown command `#{ command }`, with args beginning with: #{ formatted_args }"
end
end
end