检测在 Node.js 的网络模块中的“数据"事件上收到的完整数据 [英] Detect complete data received on 'data' Event in Net module of Node.js

查看:24
本文介绍了检测在 Node.js 的网络模块中的“数据"事件上收到的完整数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,当我们通过 TCP 发送大数据时,data 事件将分块接收.有没有一种方法可以检测到所有数据都已收到并返回完整数据.

Currently when we send a large data over TCP data event will receive it in chunks. Is there a way where we able to detect that all data is received and return complete data.

推荐答案

目前,当我们通过 TCP 数据事件发送大数据时,它会分块接收.有没有一种方法可以检测到所有数据都已收到并返回完整数据.

Currently when we send a large data over TCP data event will receive it in chunks. Is there a way where we able to detect that all data is received and return complete data.

TCP 只是一个连续的数据流.除非您关闭连接并使用关闭的连接作为数据完成的信号,否则 TCP 级别的给定传输没有开始或结束.

TCP is just a continuous stream of data. There's no start or end to a given transmission at the TCP level unless you close the connection and use a closed connection as a signal that the data finished.

因此,如果您想知道给定的数据块在哪里开始和停止,您需要在发送的数据中设计一种方式来了解这一点(基本上是构建您自己的小型迷你线格式或协议).有无数种不同的方法可以做到这一点,这就是我们在 TCP 之上构建如此多不同协议的原因之一.两个最简单的方案是:

So, if you want to know where a given chunk of data starts and stops, you need to design a way within the data you send in order to know that (essentially build your own little mini wire format or protocol). There are a zillion different ways to do that and that's one of the reason we have so many different protocols built on top of TCP. The two simplest schemes are to:

  1. 发送一定长度的数据包,然后发送那么多字节.然后接收者读取长度并知道它何时读取了那么多字节,它就拥有了整个块.

  1. Send a length of your packet and then send that many bytes. The recipient then reads the length and knows when it then reads that many bytes, it has the whole chunk.

使用某种不会出现在实际数据中的分隔符.例如,一些简单的协议使用换行符作为分隔符.您发送一堆文本,然后用换行符终止它.接收者读取数据,直到他们得到一个换行符,这告诉他们他们有一个完整的数据块.根据数据的类型,有许多可能的分隔符.

Use some sort of delimiter that won't appear in the actual data. For example, some simple protocols use a linefeed as a delimiter. You send a bunch of text and then terminate it with a linefeed. The receipient reads data until they get a linefeed and that tells them they have a complete chunk of the data. There are many possible delimiters depending upon what the type of data is.

其他协议(例如 webSocket 或 socket.io)内置了基于消息的范例,可为您完成这项工作.您在一端发送一条消息,然后在另一端接收整条消息.

Other protocols such as webSocket or socket.io have message-based paradigms built into them doing this work for you. You send a message at one end and then receive a whole message at the other end.

根据您发送的数据类型(文本/二进制)和数据的长度以及数据的字符是什么(是否有可能的分隔符),某些选项或多或少合适在实际数据中).

Some options are more or less appropriate based on the type of data (text/binary) you're sending and the length of the data and what the character of the data is (whether there are possible delimiters that won't be in the actual data).

这篇关于检测在 Node.js 的网络模块中的“数据"事件上收到的完整数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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