Lua Socket接收长度未知的字符串

我有一个Socket服务器,它监听命令并响应它们。响应的长度不总是相同的。在Python中,即使服务器的响应小于1024个字节,以下代码也可以运行。

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 9999))
sock.sendall(bytes("command\n", 'utf-8'))
print(sock.recv(1024))

现在我想将其翻译为等效的Lua代码。这是我的尝试:

socket = require("socket")
sock = socket.connect("localhost", 9999)
sock:send("command\n")
s, status, partial = sock:receive(1024)
print(s)

不幸的是,如果发送的字节数小于1024,则接收调用会阻塞。Python客户端如何找出传输何时结束?为什么Lua客户端仍在等待?

点赞
用户3555845
用户3555845

Lua receive is blocking, while python recv is non-blocking if there is at least 1 byte. The underlying tcp protocol does not guarantee that more than 1 byte is read. So it's only luck, if you receive the whole response in python. On the other side, Lua expects exactly 1024 bytes and waits until the server has send 1024 or the socket is closed.

TCP 是一种流式协议。你需要一种长度指示器或消息结束标记,比如换行符。你可以在 Lua 中写入如下代码:

s = sock:receive('*l')
2016-03-30 21:39:29