概述
本文介绍TCP粘包
服务器端代码见:
python之TCP服务器(1.1版)
1. 客户端代码如下
#coding=utf-8
import socket
s = socket.socket()
s.connect(('127.0.0.1', 9999))
data=s.recv(1024)
print('来自server的消息:',data.decode('utf-8'))
s.sendall('name:lilei'.encode('utf-8'))
s.sendall('age:20'.encode('utf-8'))
s.sendall('gender:male'.encode('utf-8'))
s.sendall('length:175cm'.encode('utf-8'))
s.close()
客户端多次发送的数据,在服务器端一次就全部接收了,这种情况就是:TCP粘包和拆包
2.客户端代码修改如下:
#coding=utf-8
import socket
s = socket.socket()
s.connect(('malaoshi.top', 9999))
data=s.recv(1024)
print('来自server的消息:',data.decode('utf-8'))
s.sendall('name:lilei'.encode('utf-8'))
s.sendall('age:20'.encode('utf-8'))
s.sendall('gender:male'.encode('utf-8'))
s.sendall('length:175cm'.encode('utf-8'))
b='''The Political Bureau of the Communist Party of China Central Committee reviewed on Thursday an intra-Party regulation on political and legal work.The regulation, the first of its kind for the Party, is part of the five-year plan (2018-22) that the CPC Central Committee mapped out in February to have an overall design for the Party's institutional construction.The regulation, as part of the Party's basic laws and regulations, stipulates the Party's leadership over political and legal affairs and translates the Party's long-term successful experience in leading the nation's political and legal work into institutional achievements, according to a statement released after the Thursday meeting.The regulation is also required by upholding and developing socialism with Chinese characteristics as well as modernizing the country's system and capacity for governance, the statement said.The Party strives to have well-established intra-Party regulations and systems in place before the centenary of the Party's founding in 2021 to advance Party-building in the new era.The meeting also highlighted the Party's leadership over political and legal affairs. That exercise of leadership is an important step that aligns the law-based governance of the country with the regulation-based governance of the Party.Xi Jinping, general secretary of the CPC Central Committee, presided over the meeting.The Party's leadership is consistent with the rule of law, as only when the Party's leadership is upheld can people's full democracy be ensured and institutionalized and law-based governance be properly advanced, the statement said.The Party explicitly maintains that judiciary institutions must exercise their power in an independent and fair manner in line with the law, it said, adding that Party organizations and leading officials at various levels must support judiciary institutions' exercise of power.The meeting called for improvement of related systems and mechanisms in implementing the intra-Party regulation, according to the statement.'''.encode('utf-8')
print('个人介绍长度:%d'%len(b))
s.sendall(b)
s.close()
为了演示粘包、拆包,这里必须发送长文
将服务器端部署在另一台计算机并运行,然后运行客户端代码,观察服务器端打印结果,发现服务器接收数据与客户端发送数据不一致,这种情况就是:TCP粘包和拆包,详细见连接:
http://www.malaoshi.top/show_1EF2UqhwMPPZ.html
