利用Socket编写TCP客户端工具访问网站时接收数据循环结束标志不是None而是按照长度
作者:互联网
代码比较简单,就是利用socket模块模拟TCP客户端,这里就是模拟浏览器发起对网站的访问,假设socket.recv(1024)所接收的内容长度大于1024字节,那么需要循环接收,那么结束的标志是什么呢?并不是None,而是按照接收到的数据长度来判断是否已经接收完整。
1 import socket 2 import sys 3 import optparse 4 5 class TCPClient: 6 def __init__(self) -> None: 7 self.target = self.get_params()[0] 8 self.port = self.get_params()[1] 9 10 def get_params(self): 11 parser = optparse.OptionParser('Usage: <Program> -t target -p port') 12 parser.add_option('-t', '--target', dest='target', type='string', help='Specify target') 13 parser.add_option('-p', '--port', dest='port', type='int', help='Specify port to connect') 14 options, args = parser.parse_args() 15 if options.target is None or options.port is None: 16 print(parser.usage) 17 sys.exit() 18 return options.target, options.port 19 20 21 def run(self): 22 try: 23 client_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 24 # client_s.settimeout(2) 25 client_s.connect((self.target, self.port)) 26 # print(client_s.recv(4096).decode('utf-8')) 27 send_data = "GET / HTTP/1.1\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0\r\n\r\n" 28 client_s.send(send_data.encode('utf-8')) 29 recv_data = "" 30 while True: 31 data = client_s.recv(1024).decode('utf-8') 32 if len(data) == 0: 33 break 34 recv_data = recv_data + data 35 print(recv_data) 36 except Exception as e: 37 print(e) 38 sys.exit() 39 40 if __name__ == '__main__': 41 tcpclient = TCPClient() 42 tcpclient.run()
标签:None,target,recv,self,socket,接收数据,data,port,Socket 来源: https://www.cnblogs.com/jason-huawen/p/16331477.html