我将 ruby 套接字用于简单的乒乓球场景。(客户端正在向服务器发送一个字符串,而服务器正在将字符串发回——仅此而已)
简单客户端:
socket = TCPSocket.new "localhost", 5555
socket.write "test-string\n"
puts socket.gets.inspect
它工作正常,直到线程发挥作用:
socket = TCPSocket.new "localhost", 5555
threads = []
5.times do |t|
threads << Thread.new(t) do |th|
socket.write "#{t}\n"
puts "THREAD: #{t} --> [ #{socket.recv(1024).inspect} ]"
end
end
threads.each { |th| th.join }
# Output: THREAD: 3 --> [ "0\r\n1\r\n2\r\n3\r\n4\r\n" ]
这里的问题是,每个线程似乎都使用 socket.gets “监听”来自服务器的响应,因此任意线程将接收来自服务器的所有响应,正如您从输出中看到的那样。最好每个线程应该收到它自己的响应,输出不应该看起来像
THREAD: 3 --> [ "0\r\n1\r\n2\r\n3\r\n4\r\n" ]
但更喜欢:
THREAD: 0 --> [ "0\r\n" ]
THREAD: 1 --> [ "1\r\n" ]
THREAD: 2 --> [ "2\r\n" ]
THREAD: 3 --> [ "3\r\n" ]
THREAD: 4 --> [ "4\r\n" ]
这里有什么交易?