socket recv 粘包 分包 长度

socket recv 粘包 分包 长度 - sei_zhouyu的日志 - 网易博客

socket recv 粘包 分包 长度   

2009-07-19 23:04:11|  分类: 并行编程 |  标签:  |字号 订阅

#这些内容老手可能不屑一顾,但是像我这种新手还一点都不懂,如果还有人比我
还新,希望对你有用
#
#

server端接收client端连接以后的3种处理方式

1.dispatching a thread to handle |clientsocket|
2.create a new process to handle |clientsocket|
3.restructure this app to use non-blocking sockets, and mulitplex
between our "server" socket and any active |clientsocket|s using |select|.


socket.recv()的方法其实是将socket的buffer中的对象取回,然后清空buff的过程
socket.send()是将数据去填充buffer
因此到底能够recv到什么东西,或者说是多少长度的数据,是由buffer的长度来决定。
情况1:
buff=100, 包1=20
包1,并且只有1个包的时候,取回的包1所有的内容
情况2:
buff=100, 包1=20, 包2=20
包1和包2在socket中连续发送,这种情况将取回包1+包2的内容(坏现象)
情况3:
buff=100, 包1=200 或者 buff=100, 包1=50, 包2=100
这种情况还没有验证,如果谁知道的话,请告诉一下。谢谢

第二种情况是大家不想看到的情况,如果才能避免,四种方法
1。messages must either be fixed length (yuck),
2。or be delimited (shrug),
3。or indicate how long they are (much better),
4。or end by shutting down the connection.
建议是采用第3种方法,根据网站上的说明,好像服务器要发2个包,第一个包确定
数据长度,第二个才是数据

原文:The easiest enhancement is to make the first character of the
message an indicator of message type, and have the type determine the
length. Now you have two |recv|s - the first to get (at least) that
first character so you can look up the length, and the second in a loop
to get the rest
原文地址:https://www.cnblogs.com/lexus/p/2852194.html