sockets - 套接字协议(protocol)基础

标签 sockets network-protocols

最近在看一篇Socket Programming HOWTO以下部分突然出现在我身上:

But if you plan to reuse your socket for further transfers, you need to realize that there is no "EOT" (End of Transfer) on a socket. I repeat: if a socket send or recv returns after handling 0 bytes, the connection has been broken. If the connection has not been broken, you may wait on a recv forever, because the socket will not tell you that there's nothing more to read (for now). Now if you think about that a bit, you'll come to realize a fundamental truth of sockets: messages must either be fixed length (yuck), or be delimited (shrug), or indicate how long they are (much better), or end by shutting down the connection. The choice is entirely yours, (but some ways are righter than others).



本节重点介绍如何编写套接字“协议(protocol)”以传递消息的 4 种可能性。我的问题是,用于实际应用的首选方法是什么?

正如文章或多或少断言的那样,通常最好在每条消息中包含消息大小(大概在标题中)?有没有其他方法更可取的情况?

最佳答案

该决定应取决于您要发送的数据(它是什么,它是如何收集的)。如果数据是固定长度的,那么固定长度的数据包可能是最好的。如果数据可以很容易地(不需要转义)分成分隔实体,那么分隔可能是好的。如果您在开始发送数据 block 时知道数据大小,那么 len-prefixing 可能会更好。如果发送的数据总是单个字符,甚至是单个位(例如“on”/“off”),那么任何不同于固定大小的单个字符消息都会太多。

还要考虑协议(protocol)可能会如何发展。只要不包含 EOL 字符本身,EOL 分隔的字符串就很好。固定长度可能会很好,直到可以使用一些可选部分等来扩展数据。

关于sockets - 套接字协议(protocol)基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2368580/

相关文章:

c++ - 新套接字的名称

c - 使用 SOCK_DGRAM 从服务器获取信息时出现问题

c++ - 发送到失败的 C++//POSIX.4

服务器地址为 FQDN 时无法打开 FTP 连接

networking - 消息中心号码、SMSC、ESME、SMPP

java - 在 IPV4 网络中使用 maven3 但抛出 IPV6 抛出 IPV6 异常

linux - 2个并行连接中socket write()的公平性?

networking - 为什么可以同时在 TCP 和 UDP 上使用同一个端口?

c++ - 如何知道同一台机器上的两个进程之间是否存在 TCP 连接?

networking - 如果您通过自己的 IP 连接到您的计算机,流量会离开您的 NIC 然后返回吗?