0

所以我的代码工作正常,除了在遍历数组并向多个聊天客户端发送响应时,每个客户端接收响应之间的延迟接近一秒。我在我的计算机上运行服务器和客户端,所以不应该有任何真正的延迟,对吧?我知道红宝石并没有这么慢。另外,为什么我的电脑的风扇在运行时会旋转?如果包含它会有所帮助,还有更多内容。

# 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
4

1 回答 1

1

除了测试if @client_join_order_array.size > client_quantity,如果它是假的,除了抽 CPU 之外什么都不做,你应该在这一点上接受新的连接,并阻塞直到有一个。换句话说,移动接受连接的代码并将它们添加到此处的数组中。

于 2013-04-12T00:53:06.887 回答