由于python的socket具备自动维护心跳包的性质,因此在C端创建连接时对短连接和长连接不做区别,只要服务端不做断开就会一直保持连接。那么使用socket库提供的函数,我们可以实现一个简单的以输入的TPS来发送数据包的函数。
def msgSendbyTPS(msg, connection, TPS):
while True:
t = time.time()
for i in range(TPS):
connection.send(msg)
time.sleep(1 + t - time.time())
此函数模拟TPS的方法是在一秒开始时尽快发送完一秒内的TPS笔报文,然后暂停至一秒结束。不适用于需要准备过于复杂的报文或是超高TPS要求的情况,需要修改。
def multiMsgSendByTPS(msg, TPS, ip, port, port2=0, port3=0, port4=0):
C1 = socket(AF_INET, SOCK_STREAM)
C1.connect((ip, port))
C2 = socket(AF_INET, SOCK_STREAM)
C2.connect((ip, port2))
C3 = socket(AF_INET, SOCK_STREAM)
C3.connect((ip, port3))
C4 = socket(AF_INET, SOCK_STREAM)
C4.connect((ip, port4))
print('succeed in connecting ...')
flag = 1
while True:
if flag == 1:msgSendbyTPS(msg, C1, TPS)
elif flag == 2:msgSendbyTPS(msg, C2, TPS)
elif flag == 3:msgSendbyTPS(msg, C3, TPS)
elif flag == 4:msgSendbyTPS(msg, C4, TPS)
else:
msgSendbyTPS(msg, C1, TPS)
flag = 1
print(length, ' msg sent through port ', flag)
flag = flag + 1
time.sleep(1 + t - time.time())