2

I am trying to create TCP client in lua

local host, port = HOST, PORT
local socket = require("socket")
client = socket.tcp();
client:connect(host, port);
client:send("Hello User");

this works fine but when i add

while true do
    local s, status, partial = client:receive()
    print(s or partial)
    if status == "closed" then break end
end

to read data from socket it block total execution of code.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Saurav
  • 248
  • 3
  • 13
  • TO be clear, is it blocking on the receive? Is it doing that even if you kill the connection? – Alex Aug 13 '13 at 15:03

1 Answers1

1

By default, all luasocket I/O operations are blocking. You need to use socket.settimeout(0) (settimeout) to disable blocking. You can then check for "timeout" value returned as status and act accordingly.

Depending on how the data is being sent, this answer may be relevant as well.

Community
  • 1
  • 1
Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • I tried settimeout(0) but by using this request is not blocking but this always return no data. – Saurav Aug 28 '13 at 08:56
  • Check the link to SO answer I included as you don't seem to add "\n" to your messages and `receive` by default expects a line terminated by newline. Since it doesn't get it, it will return no data (although it may return partial results). – Paul Kulchenko Aug 28 '13 at 15:16