套接字协议基础 [英] Socket Protocol Fundamentals

查看:97
本文介绍了套接字协议基础的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,在阅读套接字编程方法时,以下部分对我跳了起来:

Recently, while reading a Socket Programming HOWTO the following section jumped out at me:

但是,如果您打算重新使用套接字以进行进一步的传输,则需要意识到套接字上没有"EOT"(传输结束).我重复一遍:如果套接字发送或接收后处理0个字节后返回,则说明连接已断开.如果连接尚未断开,则您可能会永远等待接收,因为套接字不会告诉您(现在)没有更多内容可供阅读.现在,如果您考虑一下,您将认识到套接字的基本原理:消息必须为固定长度(很糟糕),或者为定界(耸耸肩) ),或指出连接的时间(好得多),或通过关闭连接结束.选择完全是您的选择(但某些方法比其他方法更正确).

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).

本节重点介绍了如何编写套接字协议"以传递消息的4种可能性.我的问题是,在实际应用中首选的方法是什么?

This section highlights 4 possibilities for how a socket "protocol" may be written to pass messages. My question is, what is the preferred method to use for real applications?

随着文章或多或少地断言,通常最好在每条消息中都包含消息大小(大概在标头中)吗?在任何情况下,最好使用其他方法吗?

Is it generally best to include message size with each message (presumably in a header), as the article more or less asserts? Are there any situations where another method would be preferable?

推荐答案

常见协议要么在标头中指定长度,要么被定界(例如,像HTTP).

The common protocols either specify length in the header, or are delimited (like HTTP, for instance).

请记住,这还取决于您使用TCP还是UDP套接字.由于TCP套接字是可靠的,因此可以确保将所有东西都塞进其中.使用UDP,情况就不同了,而且更加复杂.

Keep in mind that this also depends on whether you use TCP or UDP sockets. Since TCP sockets are reliable you can be sure that you get everything you shoved into them. With UDP the story is different and more complex.

这篇关于套接字协议基础的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆