所以我的代码工作正常,除了迭代数组并向多个聊天客户端发送响应时,每个客户端接收响应之间的延迟几乎是一秒钟。我在我的计算机上运行服务器和客户端,所以不应该有任何实际的延迟,对吧?我知道红宝石不是那么慢。另外,为什么我的电脑风扇在运行时会旋转?如果包含它会有所帮助,还会有更多。
# Creates a thread per client that listens for any messages and relays them to the server viewer and all the other clients.
create_client_listener_threads = Thread.new do
x = nil
client_quantity = 0
# Loops indefinitely
until x != nil
#Checks to see if clients have joined since last check.
if @client_join_order_array.size > client_quantity
# Derives number of new arrivals.
number_of_new_arrivals = @client_join_order_array.size - client_quantity
# Updates number of clients in client_quantity.
client_quantity = @client_join_order_array.size
if number_of_new_arrivals != 0
# Passes new arrivals into client for their thread creation.
@client_join_order_array[-1 * number_of_new_arrivals..-1].each do |client|
# Creates thread to handle receiving of each client's text.
client_thread = Thread.new do
loop do
text = client.acception.gets
# Displays text for server viewer.
puts "#{client.handle} @ #{Time.now} said: #{text}"
@client_hash.each_value do |value|
if value.handle != client.handle
# Displays text for everyone except server viewr and person who spoke.
value.acception.puts "#{client.handle} @ #{Time.now} said: #{text}"
end
end
end
end
end
end
end
end
end
答案 0 :(得分:1)
而不是测试if @client_join_order_array.size > client_quantity
,除了吸烟之外什么都不做,如果它是假的,那么你应该接受新的连接,并阻塞直到有一个。换句话说,移动接受连接的代码并将它们添加到数组中。