网络编程
tcp 协议套接字通信
from socket import * import subprocess import struct import json server=socket(AF_INET,SOCK_STREAM) server.bind(('127.0.0.1',8080)) server.listen(5) while True: conn,client_addr=server.accept() #(连接对象,客户端的ip和端口) print(client_addr) while True: try: cmd=conn.recv(1024) obj=subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout=obj.stdout.read() stderr=obj.stderr.read() # 1、制作报头 header_dic={ 'total_size':len(stdout) + len(stderr), 'md5':'123svsaef123sdfasdf', 'filename':'a.txt' } header_json = json.dumps(header_dic) header_bytes = header_json.encode('utf-8') # 2、先发送报头的长度 header_size=len(header_bytes) conn.send(struct.pack('i',header_size)) # 3、发送报头 conn.send(header_bytes) # 4、发送真实的数据 conn.send(stdout) conn.send(stderr) except ConnectionResetError: break conn.close() server.close()
from socket import * import struct import json client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) # print(client) while True: cmd=input('>>>: ').strip() if not cmd:continue client.send(cmd.encode('utf-8')) #1、先收报头的长度 header_size=struct.unpack('i',client.recv(4))[0] #2、接收报头 header_bytes=client.recv(header_size) #3、解析报头 header_json=header_bytes.decode('utf-8') header_dic=json.loads(header_json) print(header_dic) total_size=header_dic[ 'total_size'] # print(total_size) #1025 #4、根据报头内的信息,收取真实的数据 recv_size=0 res=b'' while recv_size < total_size: recv_data=client.recv(1024) res+=recv_data recv_size+=len(recv_data) print(res.decode('gbk')) client.close()
import struct import json header_dic = { 'total_size': 3122222222222222222222222222222222222, 'md5': '123svsaef123sdfasdf', 'filename': 'a.txt' } header_json=json.dumps(header_dic) # print(header_json,type(header_json)) header_bytes=header_json.encode('utf-8') header_size=len(header_bytes) print(header_size) obj=struct.pack('i',header_size) print(obj,len(obj))
import socket import struct import json import subprocess import os class MYTCPServer: address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 8192 coding='utf-8' request_queue_size = 5 server_dir='file_upload' def __init__(self, server_address, bind_and_activate=True): """Constructor. May be extended, do not override.""" self.server_address=server_address self.socket = socket.socket(self.address_family, self.socket_type) if bind_and_activate: try: self.server_bind() self.server_activate() except: self.server_close() raise def server_bind(self): """Called by constructor to bind the socket. """ if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(self.server_address) self.server_address = self.socket.getsockname() def server_activate(self): """Called by constructor to activate the server. """ self.socket.listen(self.request_queue_size) def server_close(self): """Called to clean-up the server. """ self.socket.close() def get_request(self): """Get the request and client address from the socket. """ return self.socket.accept() def close_request(self, request): """Called to clean up an individual request.""" request.close() def run(self): while True: self.conn,self.client_addr=self.get_request() print('from client ',self.client_addr) while True: try: head_struct = self.conn.recv(4) if not head_struct:break head_len = struct.unpack('i', head_struct)[0] head_json = self.conn.recv(head_len).decode(self.coding) head_dic = json.loads(head_json) print(head_dic) #head_dic={'cmd':'put','filename':'a.txt','filesize':123123} cmd=head_dic['cmd'] if hasattr(self,cmd): func=getattr(self,cmd) func(head_dic) except Exception: break def put(self,args): file_path=os.path.normpath(os.path.join( self.server_dir, args['filename'] )) filesize=args['filesize'] recv_size=0 print('----->',file_path) with open(file_path,'wb') as f: while recv_size < filesize: recv_data=self.conn.recv(self.max_packet_size) f.write(recv_data) recv_size+=len(recv_data) print('recvsize:%s filesize:%s' %(recv_size,filesize)) tcpserver1=MYTCPServer(('127.0.0.1',8080)) tcpserver1.run() 客户端 import socket import struct import json import os class MYTCPClient: address_family = socket.AF_INET socket_type = socket.SOCK_STREAM allow_reuse_address = False max_packet_size = 8192 coding='utf-8' request_queue_size = 5 def __init__(self, server_address, connect=True): self.server_address=server_address self.socket = socket.socket(self.address_family, self.socket_type) if connect: try: self.client_connect() except: self.client_close() raise def client_connect(self): self.socket.connect(self.server_address) def client_close(self): self.socket.close() def run(self): while True: inp=input(">>: ").strip() if not inp:continue l=inp.split() cmd=l[0] if hasattr(self,cmd): func=getattr(self,cmd) func(l) def put(self,args): cmd=args[0] filename=args[1] if not os.path.isfile(filename): print('file:%s is not exists' %filename) return else: filesize=os.path.getsize(filename) head_dic={'cmd':cmd,'filename':os.path.basename(filename),'filesize':filesize} print(head_dic) head_json=json.dumps(head_dic) head_json_bytes=bytes(head_json,encoding=self.coding) head_struct=struct.pack('i',len(head_json_bytes)) self.socket.send(head_struct) self.socket.send(head_json_bytes) send_size=0 with open(filename,'rb') as f: for line in f: self.socket.send(line) send_size+=len(line) print(send_size) else: print('upload successful') client=MYTCPClient(('127.0.0.1',8080)) client.run()
udp套接字通信
import socket server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议 server.bind(('127.0.0.1',8080)) while True: client_data,client_addr=server.recvfrom(1024) msg=input('回复%s:%s>>>:' %(client_addr[0],client_addr[1])) server.sendto(msg.encode('utf-8'),client_addr) 客户端 import socket client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议 while True: msg=input('>>>: ').strip() client.sendto(msg.encode('utf-8'),('127.0.0.1',8080)) res,server_addr=client.recvfrom(1024) print(res.decode('utf-8'))