【问题标题】:What does "unconnected:sendto() " return value mean?“unconnected:sendto()”返回值是什么意思?
【发布时间】:2016-07-04 16:23:46
【问题描述】:

LuaSocket 文档说:

unconnected:sendto(datagram, ip, port)

如果成功,该方法返回1。如果错误,该方法 返回 nil 后跟错误消息。

但我得到的值为44的返回值是什么意思?

我的代码在这里:

local socket = require("socket")

udp = socket.udp()
udp:setsockname("*", 8080)

local msg = "Test"

m=assert(udp:sendto( msg, "228.192.1.1", 8080))
print(m)

【问题讨论】:

    标签: lua udp return-value luasocket


    【解决方案1】:

    仔细查看the source 内部udp.csendo 方法

    static int meth_sendto(lua_State *L) {
        p_udp udp = (p_udp) auxiliar_checkclass(L, "udp{unconnected}", 1);
        size_t count, sent = 0;
        const char *data = luaL_checklstring(L, 2, &count);
        const char *ip = luaL_checkstring(L, 3);
        const char *port = luaL_checkstring(L, 4);
        p_timeout tm = &udp->tm;
        int err;
        struct addrinfo aihint;
        struct addrinfo *ai;
        memset(&aihint, 0, sizeof(aihint));
        aihint.ai_family = udp->family;
        aihint.ai_socktype = SOCK_DGRAM;
        aihint.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
        err = getaddrinfo(ip, port, &aihint, &ai);
        if (err) {
            lua_pushnil(L);
            lua_pushstring(L, gai_strerror(err));
            return 2;
        }
        timeout_markstart(tm);
        err = socket_sendto(&udp->sock, data, count, &sent, ai->ai_addr,
            (socklen_t) ai->ai_addrlen, tm);
        freeaddrinfo(ai);
        if (err != IO_DONE) {
            lua_pushnil(L);
            lua_pushstring(L, udp_strerror(err));
            return 2;
        }
        lua_pushnumber(L, (lua_Number) sent);
        return 1;
    }
    

    基本上,文档的“returns 1”语句是错误的。代码中return 1语句的意思是实际函数返回一个值,实际上是压入栈中的:

    lua_pushnumber(L, (lua_Number) sent);
    

    变量sent 仅在上面的几个语句中计算出来(检查socket_sendto 调用。

    所以,返回的4 正是@moteus commented发送的字节数

    【讨论】:

      【解决方案2】:

      sendto 返回number of bytes sent

      【讨论】:

        猜你喜欢
        • 2013-04-25
        • 2014-05-16
        • 1970-01-01
        • 1970-01-01
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        相关资源
        最近更新 更多