如何在 SwiftNIO TCP 服务器和基于 Python 的 TCP 客户端之间传输数据?

How to transfer data between SwiftNIO TCP-server and Python based TCP-client?

我有一个用 SwiftNIO 编写的 TCP 服务器,基于此 documentation

我希望我的客户端用 python 编写,我可以从中发送多个 JSON 字符串并且可以接收 similar/different 多个 JSON 字符串作为定期响应几分钟。

我需要将来自 python 客户端的 JSON 字符串转换为哪种格式以及如何在 SwiftNIO 服务器上获得相同的 JSON 字符串(反之亦然)?

如果我是你,我会使用 Vapor web server and any Python HTTP library such as requests. If you do that, then your job will be pretty straightforward. The Vapor community is also super helpful in their Discord chat 的 HTTP。

如果你真的想在像 SwiftNIO 这样的 low-level 库中做到这一点,那当然是可能的,但你需要为框架设计一个所谓的“有线协议”(即什么时候做一个JSON 消息开始和结束)。 SwiftNIO 非常适合这些事情,但您可能需要学习很多东西。

例如,您可以使用 NIO Extras 的 LineBasedFrameDecoder and send each JSON (make sure it doesn't contain newlines) followed by a \n. Or you could say that you prepend the JSON by say a 32 bit length field (which you could decode using the LengthFieldBasedFrameDecoder。有很多选择...

您还可以实施 JSON-RPC and you could get some inside in this example which is also explained in this talk