Erlang網絡編程-packet參數

gen_tcp:listen(Port, Options),Options 爲一個參數列表

之前介紹過 {active, Boolean} 這個 opt,現在介紹一下 {packet, PacketType}

[quote]{packet, PacketType} (TCP/IP sockets)
Defines the type of packets to use for a socket. The following values are valid:
raw | 0
No packaging is done.
1 | 2 | 4
Packets consist of a header specifying the number of bytes in the packet, followed by that number of bytes. The length of header can be one, two, or four bytes; the order of the bytes is big-endian. Each send operation will generate the header, and the header will be stripped off on each receive operation.
asn1 | cdr | sunrm | fcgi | tpkt | line
These packet types only have effect on receiving. When sending a packet, it is the responsibility of the application to supply a correct header. On receiving, however, there will be one message sent to the controlling process for each complete packet received, and, similarly, each call to gen_tcp:recv/2,3 returns one complete packet. The header is not stripped off.
The meanings of the packet types are as follows:
asn1 - ASN.1 BER,
sunrm - Sun's RPC encoding,
cdr - CORBA (GIOP 1.1),
fcgi - Fast CGI,
tpkt - TPKT format [RFC1006],
line - Line mode, a packet is a line terminated with newline, lines longer than the receive buffer are truncated.[/quote]

[url=http://avindev.iteye.com/admin/show/65627]之前[/url]介紹過一個愚蠢的方案,用於演示Binary的匹配。現在完全可以這樣做:

gen_tcp:listen(Port, [binary, {active, true}, {packet, 2}])
...
receive
{tcp, Socket, Binary} ->
...

這樣主動發送過來的Binary,就是一個完整的Body,不包含頭部的Size信息,也無需自行處理tcp packet的完整性問題。

此外它還支持 asn1 | cdr | sunrm | fcgi | tpkt | line 這些協議,大大方便開發
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章