-1

I have an asic computer in my house that I don't really have control over, but I can talk to its API over TCP (CGminer OS). I'm trying to record data from it:

socket = TCPSocket.open(address, port)
loop do 
  sleep 1   
  socket.write(command)
  response = socket.read
end

The first iteration of this loop returns the data as expected, the second is an empty string. I'm pretty clueless about sockets and not sure what I need to do. I know I can reopen the socket each iteration if I have to, I'm just hoping I don't need to.

NoobException
  • 616
  • 9
  • 20
  • What do you expect it to return on the second read? – Steve Madsen Jul 27 '18 at 01:00
  • Stringified JSON, which is what the first read returns (it's the same command( – NoobException Jul 27 '18 at 01:02
  • `read` returns empty string on EOF. Are you sure the other endpoint isn't closing the connection after it sends its JSON payload? Can you verify with `nc` or `telnet` what its protocol is? – Amadan Jul 27 '18 at 02:08
  • @Amadan I am pretty sure it is closing the connection. JSON sorta implies RESTful, which means the socket won’t stay there listening to the upcoming input. I would reopen the socket every single time and I am not sure I understand the reasons behind the unwillingness to do so. – Aleksei Matiushkin Jul 27 '18 at 04:37
  • Even better would be if this API had a spec. Then we wouldn't need to speculate. So what's the API, and where are the docs for it? That's the first place to look IMO. Otherwise testing manually like Amadan suggest should give enough clues already. But docs are the ones you look at first. – Casper Jul 27 '18 at 07:25
  • I'm not suggesting this is a permanent solution, but if you add another `sleep` in between your `write` and `read`, does that fix it? Socket reads may be non-blocking, in which case your `read` will return only as much data as is available. If your application level protocol expects more, it's your responsibility to make additional `read` calls until it has enough data. I'm wondering if your second loop is simply reading too fast, before the remote end has sent any data back. Another thing to try is observing the behavior interactively using `telnet`. – Steve Madsen Aug 09 '18 at 21:02

1 Answers1

-1

Solution is to just reopen the socket.

loop do
  socket = TCPSocket.open(address, port)
  response = socket.read
  socket.close
end 
NoobException
  • 616
  • 9
  • 20
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/20424446) – Seanny123 Jul 27 '18 at 17:03
  • 1
    @Seanny123 This answer comes from OP, and is probably correct, though not very detailed. Which also applies to the question itself, and that is the real problem IMO. – tevemadar Jul 27 '18 at 18:58