Erlang get_tcp:recv数据长度 [英] Erlang get_tcp:recv data length

查看:253
本文介绍了Erlang get_tcp:recv数据长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用户 gen_tcp:recv(Socket,0)。为数据可接收,但我可以只接收1418字节1次。如何发送数据?

I user gen_tcp:recv(Socket, 0). for data receiveng, but i can receive only 1418 bytes for 1 time. How can I receive how much data was sent?

推荐答案

gen_tcp:recv(Socket,0) 你正在询问内核:给我所有的数据现在在接收缓冲区。内核也可以免费给你。即使是一个相当快速的链接,您也可能在TCP连接上点击慢启动,所以一开始你不会收到太多的数据。

in gen_tcp:recv(Socket, 0) you are asking the kernel: "Give me all data there is available right now in the receive buffer". The kernel is also free to give you less however. Even for a rather fast link, you will probably hit slow start on the TCP connection so in the beginning you will not get much data.

解决方案是自己做缓冲。您必须从底层套接字中获取数据,直到您已经足够构建消息为止。由于这个原因,二进制协议实现自己的消息传递是很常见的。

The solution is to do your own buffering. You will have to eat data from the underlying socket until you have enough to construct a message. It is quite common for binary protocols to implement their own kind of messaging on top of the stream due to this.

长期记录:常见的消息格式是将消息编码为:

For the longer term record: A common message format is to encode a message as:

decode(Bin) when is_binary(Bin) ->
  <<Len:32/integer, R/binary>> = Bin,
  <<Payload:Len/binary, Remain/binary>>,
  {msg, {Len, Payload}, Remaining}.

也就是说,消息是4个字节,表示一个32位的bigendian整数,后面是有效负载,长度由整数给出。这种格式和其他喜欢的格式是非常常见的,Erlang包括直接在C层中优化的解析器。要访问这些,您可以通过 inet / setops / 2 在套接字上设置选项,在我们的例子中,我们设置 {packet,4} code>。然后我们可以通过在套接字上设置 {active,once} 来获取消息,并等待下一条消息。当它到达时,我们可以在套接字上再次 {active,once} 以获取下一条消息,依此类推。如果您正确安装了Erlang手册页,则有 gen_tcp erl -man gen_tcp )的文档中的示例)

That is, messages are 4 bytes representing a 32-bit bigendian integer followed by the payload, where the length is given by the integer. This format, and others like it, are so common Erlang includes optimized parsers for it directly in the C-layer. To get access to these, you set options on the socket through inet/setops/2, in our case we set {packet, 4}. Then we can get messages by setting {active, once} on the socket and wait for the next message. When it arrives, we can {active, once} again on the socket to get the next message, and so on. There is an example in the documentation of gen_tcp (erl -man gen_tcp if you have the Erlang man-pages installed appropriately).

其他常见格式是asn.1甚至http标头(!)。

Other common formats are asn.1 or even http headers(!).

创建一个独立的进程通常是有益的,可以对您的消息格式进行编码和解码,然后将数据发送到系统的其余部分。通常,Erlang中的一个很好的解决方案是尽可能快地解析输入数据,并获取数据到一个可以处理其余问题的进程。

It is often beneficial to create a process which is separate that can encode and decode your message format and then send on data to the rest of the system. Usually a good solution in Erlang is to demux incoming data as fast as possible and get the data to a process which can then handle the rest of the problem.

这篇关于Erlang get_tcp:recv数据长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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