-->
Page 1 of 1

writing to socket from functions does not work (?)

PostPosted: Wed Dec 17, 2014 4:51 pm
by NaAl
Hi,
I am new to lua so be bear with me :)
this works (server gets HELLO):
Code: Select allsk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(5555,"192.168.1.8")
sk:send("HELLO")
sk:close()
print("sent to server")


but for some reason if I put the code in a function, the server never gets the "HELLO", e.g.:
Code: Select allfunction test()
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(5555,"192.168.1.8")
sk:send("HELLO")
sk:close()
print("sent to server")
end
test()

Re: writing to socket from functions does not work (?)

PostPosted: Fri Dec 19, 2014 2:32 am
by ThomasW
NaAl wrote:Hi,
I am new to lua so be bear with me :)
this works (server gets HELLO):
Code: Select allsk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(5555,"192.168.1.8")
sk:send("HELLO")
sk:close()
print("sent to server")


but for some reason if I put the code in a function, the server never gets the "HELLO", e.g.:
Code: Select all1 function test()
2 sk=net.createConnection(net.TCP, 0)
3 sk:on("receive", function(sck, c) print(c) end )
4 sk:connect(5555,"192.168.1.8")
5 sk:send("HELLO")
6 sk:close()
7 print("sent to server")
8 end
9 test()


I am wondering why any version even worked once ;) You're closing the connection too fast - immediately after requesting the 'send'. But the program flow reaching line 6 doesn't mean at all that the data has actually been sent out - it has just been passed to the tcp-stack. If you're sending small amounts of data, it would be ok to just add a
Code: Select allsk:on("sent", function(sck) sck:close() end )

and remove the close() in line 6. Keep in mind that any code that you want to be executed after the *actual* sent has to go into this function also - *not* around line 7...

Thomas

Re: writing to socket from functions does not work (?)

PostPosted: Sun Dec 21, 2014 12:31 pm
by NaAl
Thank you Thomas :D .

That was it.
/N