function Server:run()
print("Running.")
self.running = true
while self.running do
if self.client == nil then
print("Waiting for client.")
self.client = self.server:accept()
print("Client connected.")
self.client:settimeout(10)
end
local line, err = self.client:receive()
if err then
print("Error: " .. err)
elseif line == "quit" then
print("Quitting.")
self.client:close()
self.running = false
else
print("Received: " .. line)
end
end
self:terminate()
end
I expect the program to get to self.client:receive() and then wait there until it either gets a message from the client or times out after 10 seconds. However, this is not the behaviour I experience.
Instead, I just get a constant spamming of the error message "Error: timeout" as though the program is not waiting at all.
I expect the program to get to self.client:receive() and then wait there until it either gets a message from the client or times out after 10 seconds. However, this is not the behaviour I experience.
Instead, I just get a constant spamming of the error message "Error: timeout" as though the program is not waiting at all.
Well luasocket tries to receive, and after 10 seconds it timesout... so that's an error in the reception right? luasocket returns "false" followed by the error message... and the error was "timeout", so in your code you do:
local line, err = self.client:receive()
if err then
print("Error: " .. err)
elseif line == "quit" then
print("Quitting.")
self.client:close()
self.running = false
else
print("Received: " .. line)
end
end
err has a value ("timeout") so the first part executes and prints "Error: timeout". Is that your problem?
You can just ignore timeout errors by doing
local line, err = self.client:receive()
if err and err ~= "timeout" then
print("Error: " .. err)
elseif line == "quit" then
print("Quitting.")
self.client:close()
self.running = false
else
print("Received: " .. line)
end
end
Also I dont recommend setting the timeout of the client but the server instead so I would do
I have a question, is this timeout needed? your code doesnt quit when it times out, it tries to receive again.
After it timesout it prints the error and then "while self.running do" will be true so it will do everything again.
So if timeout does nothing more than a print you can just ignore it...
I would like to mention you're checking for errors wrong, you should check the truthiness of line, not of err. That said, unless luasocket is acting really weirdly, that shouldn't matter.