我一直在尝试通过 NodeMCU 平台上的 TCP 模块安装自定义协议(protocol)。但是,我尝试嵌入 TCP 数据段的协议(protocol)是二进制的,而不是基于 ASCII 的(例如 HTTP),因此有时它包含一个 NULL 字符(字节 0x00)结束 TCP 模块实现中的 C 字符串,导致数据包中的部分消息丢失。
-- server listens on 80, if data received, print data to console and send "hello world" back to caller
-- 30s time out for a inactive client
sv = net.createServer(net.TCP, 30)
function receiver(sck, data)
print(data)
sck:close()
end
if sv then
sv:listen(80, function(conn)
conn:on("receive", receiver)
conn:send("hello world")
end)
end
*这是一个简单的示例,如您所见,“receiver”变量是一个回调函数,它打印监听器检索到的 TCP 段中的数据。
如何解决这个问题?有没有办法使用 NodeMCU 库来避免这种情况?或者我是否必须实现另一个 TCP 模块或修改当前的实现以支持数组或表作为返回值而不是使用字符串?
如有任何建议,我们将不胜感激。
最佳答案
您在回调中收到的数据不应被截断。您可以通过如下更改代码来自行检查:
function receiver(sck, data)
print("Len: " .. #data)
print(data)
sck:close()
end
你会观察到,虽然数据确实只打印到第一个零字节(通过 print()
- 函数),但整个数据都存在于 LUA-String 数据
,您可以使用 8 位安全(和零字节安全)方法正确处理它。
虽然将 print()
函数修改为零字节安全应该很容易,但我不认为这是一个错误,因为打印函数是用于文本的。如果要将二进制数据写入串口,使用uart.write()
,即
uart.write(0, data)
关于c - 如何使用 NodeMCU 通过 TCP 发送/接收二进制数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43939860/