我正在做一个项目,我已经实现了一个TCP客户端服务器的设备通信。为了从服务器向客户端发送命令,我正在构建一个设备理解并发送给它的命令,但响应不是应该返回的
while 1
Thread.start(@otd.accept) do |client|
loop do
command_to_send ="<R-2,3,4>"
client.puts command_to_send
puts "Command #{command_to_send}sent"
#sleep 2
response = **client.gets** # here it halts and never puts the the next statement.
puts "Reponse #{response}"
end # end of nested loop
client.close
end #END OF THREAD.
end #end of while loop
谁能告诉我我错过了什么? 不要使用gets,因为它期望'n'作为消息的分隔符。请使用:recv,这是一个可以帮助您的方法:
def read(timeout = 2, buffer = 1024)
message = ''
begin
Timeout::timeout(timeout) do
buffer = client.recv(buffer)
message += buffer
end
rescue Timeout::Error
puts "Received nothing from client: #{client.__id__}"
message = ''
rescue Exception => e
raise "Client failed to read for reason - #{e.message}"
end
message
end
你不需要再使用sleep,因为recv像gets是阻塞。但是超时确保您不会等待不存在的响应。