-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer-dm.rb
More file actions
74 lines (64 loc) · 1.69 KB
/
Copy pathChatServer-dm.rb
File metadata and controls
74 lines (64 loc) · 1.69 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
65
require 'gserver'
def daemonize
fork do
Process.setsid
exit if fork
Dir.chdir('/')
STDIN.reopen('/dev/null')
STDOUT.reopen('/dev/null', 'a')
STDERR.reopen('/dev/null', 'a')
trap("TERM") { exit }
yield
end
end
daemonize do
class ChatServer < GServer
def initialize(*args)
super(*args)
# Keep an overall record of the client IDs allocated
# and the lines of chat
@@client_id = 0
@@chat = []
end
def serve(io)
# Increment the client ID so each client gets a unique ID
@@client_id += 1
my_client_id = @@client_id
my_position = @@chat.size
io.puts("Welcome to the chat, client #{@@client_id}!")
# Leave a message on the chat queue to signify this client
# has joined the chat
@@chat << [my_client_id, "<joins the chat>"]
loop do
# Every 5 seconds check to see if we are receiving any data
if IO.select([io], nil, nil, 2)
# If so, retrieve the data and process it...
line = io.gets
# If the user says 'quit', disconnect them
if line =~ /quit/
@@chat << [my_client_id, "<leaves the chat>"]
break
end
# Shut down the server if we hear 'shutdown'
self.stop if line =~ /shutdown/
# Add the client's text to the chat array along with the
# client's ID
@@chat << [my_client_id, line]
else
# No data, so print any new lines from the chat stream
@@chat[my_position..(@@chat.size - 1)].each_with_index do |line, index|
io.puts("#{line[0]} says: #{line[1]}")
end
# Move the position to one past the end of the array
my_position = @@chat.size
end
end
end
end
server = ChatServer.new(1235, '127.0.0.1')
server.start
loop do
break if server.stopped?
end
end
puts "The daemon process has been launched!"