我正在编写的 ruby 服务器出现问题。
服务器运行良好,直到您连接了多个客户端,然后它以类似循环的方式发送消息,当我希望所有客户端同时收到消息时。
服务器本应获取所有连接的客户端,但要等到我发出命令。问题是只有一个客户端正在获取命令,当我再次输入命令时,另一个客户端会获取命令,依此类推
服务器
require 'socket'
mutex = Mutex.new
cv = ConditionVariable.new
server = TCPServer.open(2000)
@Comm="test"
Thread.new{
loop {
Thread.start(server.accept) do |client|
client.puts("Client accepted")
mutex.synchronize {
cv.wait(mutex)
client.puts("#@Comm")
client.close
}
end
}
}
loop {
system "clear" or system "cls"
print("Enter Command\n")
@Comm = gets()
mutex.synchronize {
cv.signal
}
}
客户
require 'socket' # Sockets are in standard library
hostname = 'localhost'
port = 2000
loop {
begin
s = TCPSocket.open(hostname, port)
system "clear" or system "cls"
while line = s.gets # Read lines from the socket
puts line.chop # And print with platform line terminator
end
s.close
rescue
next
end
sleep(0.5)
}
最佳答案
在 ConditionVariable 上使用 .signal
只会唤醒一个线程,但是 .broadcast
会去唤醒所有等待信号的线程。
关于Ruby - 多线程 TCP 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42940565/