为 tcp 连接建立边界的正确方法 [英] Proper way to establish boundaries for a tcp connection

查看:27
本文介绍了为 tcp 连接建立边界的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于正确处理使用 tcp 连接接收到的数据的方法.事实上,通过建立一个 tcp 连接,一个 Stream 被创建.假设我想发送一个有开始和结束的消息.由于数据在没有指定任何边界的情况下在流中流动,我如何识别消息的开头和结尾.我想在我的消息的开头和结尾放置一些特殊字符以便识别它们,但我想知道这是否是一种正确的方法.因此,我的问题是如何为 tcp 连接正确建立消息边界?(我在客户端使用 Node.js,在服务器端使用 java)

My question is about the way to properly treat data that are received by using a tcp connection. In fact by establishing a tcp connection a Stream is created.Suppose I want to send a message which has a beginning and an end. As the data are flowing in the stream without specifying any boundaries, how can i identify the beginning and the end of a message. I thought to put some special characters at the beginning and at the end of my message in order to recognize them but I wonder if it is a proper way to do. My question is therefore how can i properly establish boundaries to a message for a tcp connection? (I'm using Node.js for client side and java for server side)

先谢谢你

推荐答案

一个普通的 TCP 连接需要某种协议来定义数据格式,以便接收端知道如何解释正在发送的内容.例如,http 是一种这样的协议,webSocket 是另一种.现有的协议有数千种.我建议您找到一个与您想做的事情非常匹配的产品并使用它,而不是构建您自己的产品.

A plain TCP connection needs some sort of protocol which defines the data format so the receiving end knows how to interpret what is being sent. For example, http is one such protocol, webSocket is another. There are thousands of existing protocols. I'd suggest you find one that is a good match for what you want to do and use it rather than building your own.

不同的协议使用不同的方案来定义数据格式,因此描述数据片段的方式也不同.例如在 http 中,它使用 \n 来描述标题,然后在每一行使用 xxxx: yyyy ,然后使用一个空行来描述标题的结尾.

Different protocols use different schemes for defining the data format and thus different ways of delineating pieces of your data. For example in http, it uses \n to delineate headers and then use xxxx: yyyy on each line and then uses a blank line to delineate the end of the headers.

其他协议使用二进制格式定义带有消息类型、消息长度和消息负载的消息包.

Other protocols use a binary format that define message packets with a message type, a message length and a message payload.

实际上有数百种不同的方法可以做到这一点.由于有很多预先构建的选择,人们通常可以找到一个合适的现有协议,并为每一端使用预先构建的服务器和客户端,而不是编写自己的协议生成和解析代码.

There are literally hundreds of different ways to do it. Since there are so many pre-built choices out there, one can usually find an existing protocol that is a decent match and use a pre-built server and client for each end rather than writing your own protocol generating and parsing code.

这篇关于为 tcp 连接建立边界的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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