-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.rb
More file actions
66 lines (55 loc) · 1.35 KB
/
Server.rb
File metadata and controls
66 lines (55 loc) · 1.35 KB
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
require 'thread'
require "socket"
class Pool
def initialize(size)
@size = size
@jobs = Queue.new
@pool = Array.new(@size) do |i|
Thread.new do
Thread.current[:id] = i
catch(:exit) do
loop do
job, args = @jobs.pop
job.call(*args)
end
end
end
end
end
# ### Work scheduling
# To schedule a piece of work to be done is to say to the `Pool` that you
# want something done.
def schedule(*args, &block)
@jobs << [block, args]
end
def shutdown
@size.times do
schedule { throw :exit }
end
@pool.map(&:join)
end
end
if $0 == __FILE__
port = 2631
host_ip = Socket.ip_address_list.find { |ai| ai.ipv4? && !ai.ipv4_loopback? }.ip_address
server = TCPServer.new(host_ip, port)
p = Pool.new(10)
loop do
p.schedule(server.accept) do |client|
message = client.gets
if message[0..3] == "HELO"
client.puts"#{message}IP:#{host_ip}\nPort:#{port}\nStudentID:11374331"
client.close
elsif message == "KILL_SERVICE\n"
client.puts("Service Killed")
client.close
server.close
else
client.puts("Aw you put your own message! I'm just going to say Hey! Bye..")
client.close
end
end
end
server.close
at_exit { p.shutdown }
end