-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.rb
More file actions
66 lines (56 loc) · 1.84 KB
/
ChatServer.rb
File metadata and controls
66 lines (56 loc) · 1.84 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
66
#!/usr/bin/env ruby
require 'gserver'
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, 0)
# If so, retrieve the data and process it...
line = io.gets
# If the user say 'quit', disconnect them
if line =~ /quit/
@@chat << [my_client_id, "<leave the chat>"]
#puts "#{@@chat[size - 1][0]} says: #{@@chat[size - 1][1]}"
puts "#{@@chat[@@chat.size - 1][0]} said: #{@@chat[@@chat.size - 1][1]}"
break
end
# Shut down the server if we hear 'shutdown'
if line =~ /shutdown/
puts "Server has been shutdown!"
self.stop
end
# 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
puts "Serve Method is stopped!"
end
end
server = ChatServer.new(1234)
server.start
loop do
break if server.stopped?
end