Ruby TCP客户端服务器

时间:2014-06-19 06:28:21

标签: ruby tcp

我正在开发一个项目,我已经为设备通信实现了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

有人可以告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

不要使用获取,因为它需要'\ 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

你不必再使用睡眠,因为像get一样阻止了。但超时确保您不会等待不存在的响应。