在 TCP 流中发送消息 [英] Sending Messages in a TCP Stream

查看:30
本文介绍了在 TCP 流中发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TCP 是基于流的,这意味着您发送的字节不一定包含在消息"中,因此接收方可能会收到半条消息或三分之二的消息.

TCP is stream-based, which means you send bytes without them necessarily being in a "message", so the receiver may get half a message or one and two thirds of messages.

因此,在每条消息都是固定大小的游戏中,如果我收到消息的一部分,我可以将其保存在缓冲区中,直到收到另一部分.这有点乏味,但是还有其他基于消息的可靠协议吗?可能有,但没有像 TCP 和 UDP 那样在操作系统中实现,所以我必须使用一些库,只要它易于使用就可以了.

So in something like a game where each message is fixed-size, if I receive a portion of a message I could just keep it in a buffer until I receive the other part. This is a bit tedious, but is there any other message-based reliable protocol? There probably are, but none are implemented in the OS as with TCP and UDP, so I'll have to use some library, which is fine as long as it's easy to use.

我总是可以制作一个可靠的 UDP 协议.你有什么建议?

I could always make a somewhat-reliable UDP protocol. Which do you suggest?

推荐答案

您可以通过 UDP 实现自己的基于 ACK 的协议.在发送方在消息前添加消息/序列号,并将该号码回显给接收方的发送方.在发送端为每条消息启动一个计时器,并在您收到相应的 ACK 时取消它.如果计时器弹出,请重新发送消息.

You could implement your own ACK-based protocol over UDP. Prepend the message with a message/sequence number on the sending side and echo that number back to the sender on the receiving side. Start a timer on the sending side for each message and cancel it when you get the corresponding ACK back. If the timer pops, re-send the message.

XMPP 对于这个应用程序来说太重了.

XMPP is way, way too heavy for this application.

这篇关于在 TCP 流中发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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