Best method to use TCPSocket


I’m having an issue getting an expected response via TCPSocket. My goal
is to connect to a remote controller device and access XML data.

The following code properly authenticates a connection, however I am not
getting the response I expect.


require “socket”

#set proxy server
host = “host” #removed specifics
port = “port” #removed specifics

#set parameters for send message
user = “XXX” #removed specifics
pass = “XXX” #removed specifics
mac = “XXX” #removed specifics
limit = 10
start_time = “20100910_120000”
end_time = “20100910_123000”

#format the send message required
message = “User: #{user}
Pass: #{pass}
MAC: #{mac}
Limit: #{limit}
Start: #{start_time}
End: #{end_time}

#open TCP socket
s =, port)

#send the message to controller

#read and print the response (specify number of bytes)
xml = s.recv(1000)
puts xml

#close the socket

This code outputs: at your service, [draker.labs]”

However, the manufacturer is showing the XML that I should be able to
access in his debug file

“SensorQueryReader] constructBean Finish
2010-09-15 13:57:06,473 DEBUG [Thread-18837]
[] constructBean draker.labs was
2010-09-15 13:57:06,478 INFO [Thread-18837]
[] writeXML Found 2 data sets for
00:90:c2:db:7a:e8 from 2010-09-10 12:00:00.0 to 2010-09-10 12:30:00.0
2010-09-15 13:57:06,478 INFO [Thread-18837]
[] writeXML
2010-09-10 12:19:01.0197.64154.8160.4159.04165.3164.2181.9517.580.059.54138.90959
2010-09-15 13:57:06,478 INFO [Thread-18837]
[] writeXML Finished writing XML
2010-09-15 13:57:06,478 INFO [Thread-18837]
[] run Connection 143 closed”

Any ideas why I’m not able to see the outputed XML like shown in the
debug message? Any help is much appreciated.



Don’t use recv on a TCP socket.

  • Use read(n) if you know you need to read exactly n bytes.
  • Use read() if you want to read until the other end closes the socket.
  • Use gets() if you want to read up to the next end-of-line.

As a last resort, you can use readpartial(n) to get however many bytes
are available in the receive buffer at the time, between 1 and n. But
you’ll need to repeat this until you’re sure you have the complete

Which to use depends on how the other end frames its response. I’d try
read(), on the assumption that the other end sends its response and then
closes the socket.