I am writing an app taking a开发者_开发知识库dvantage of Lua Socket lib. Here is a simple code snippet that describes my problem.
local com=require("socket");
local socket=com.tcp();
local hello="hi stack overflow";
local myIP="192.168.1.1";
local myPort = 2000;
local err = nil;
-- Main
while 1
if(~err) then
err = socket:send(hello);
else
if(socket:connect("myIP", myPort))) then
err = 1;
end -- second if
end -- first if
waitfor(10); -- wait for 10 sec.
do
(I actually didn't run this particular code but it is identical to the running code in my problem). When I see that if socket is closed, this code cannot reopen it. I would have guessed once we grab the master TCP object we can open and close as we please.
I can force this code to work by repeating the socket.tcp() call however I suspect that leaves the previous object somewhere in memory and I want to avoid this.
Well, things that are wrong in your code (starting from the top)
- It's a bad habbit reusing default module names like socket, it'll confuse people reading your code
- While loop syntax is
while <condition> do <statements> end
- setting err to nil is useless in this case, as it does not exist in the snippet scope
- it makes no sense to send to an unconnected master.
- negation is done with
not
instead of~
- you pass the string "myIP" instead of the actual IP
then there's also a function socket.sleep()
you might be interested in.
I'm wondering why you complicate the loop this way, and don't just use something like:
require("socket");
local soc=socket.tcp();
local hello="hi stack overflow";
local myIP="192.168.1.1";
local myPort = 2000;
local stat,err=socket:connect(myIP, myPort)
if not stat then
error(err)
else
-- Main
while not err do
err = socket:send(hello)
socket.sleep(10)
end
end
The connect call will never work as you are passing the string "myIP" not the variable myIP
which contains your target Ip address.
精彩评论