简体   繁体   中英

LuaSocket - TCP 2nd message not sending

I've been searching Google for awhile and there seems to be no offers on fixing this problem I have here.

I am using LuaSocket as a simple way to connect to a external server I created, and I am able to connect to it successfully and send a signal.

However, when I try to send a second message later on, the external server does not seem to be receiving the message, even though I am still connected to the socket.

socket = require("socket")
host, port = ip, port
tcp = assert(socket.tcp())
tcp:settimeout( 0 )

tcp:connect(host, port);

msg = {
    ["status"]="connect",
    ["usrName"]=username
}
msg = Json.Encode(msg)

tcp:send(msg); -- This message, the server received this message.


-- Later in my code, I attempt to send another message.

msg = {
    ["status"]="anotherMessage",
    ["usrName"]=username
};
msg = Json.Encode(msg) 
tcp:send(msg); -- This message is not sending, even though i'm still connected.

You need to show what happens on the other side as it may be simply not reading even though the connection may be open. You also don't say what exactly happens when "message is not sending"; do you get an error? the script finishes but the message is not sent?

There are several things you can try:

  • Switch to the (default) synchronous send until you get it working; remove tcp:settimeout(0) , as your send may simply fail with "timeout" message if the other side is not ready to read the message.
  • Check the error message from :send call to see if it's timing out or not.

    local ok, err = tcp:send(msg)

  • Use socket.select to check if the other side it ready to accept the message you are sending.

尝试在序列化JSON的末尾添加"\\r\\n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM