标签:ons res encoding 执行 父类 roc 自己 encode 关系
FTP作业:上传下载文件
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() #下列代码与本题无关 class MYUDPServer: """UDP server class.""" address_family = socket.AF_INET socket_type = socket.SOCK_DGRAM allow_reuse_address = False max_packet_size = 8192 coding=‘utf-8‘ def get_request(self): data, client_addr = self.socket.recvfrom(self.max_packet_size) return (data, self.socket), client_addr def server_activate(self): # No need to call listen() for UDP. pass def shutdown_request(self, request): # No need to shutdown anything. self.close_request(request) def close_request(self, request): # No need to close anything. pass
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()
如果你想在分布式系统中实现一个简单的客户端链接认证功能,又不像SSL那么复杂,那么利用hmac+加盐的方式来实现
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ from socket import * import hmac,os secret_key=b‘linhaifeng bang bang bang‘ def conn_auth(conn): ‘‘‘ 认证客户端链接 :param conn: :return: ‘‘‘ print(‘开始验证新链接的合法性‘) msg=os.urandom(32) conn.sendall(msg) h=hmac.new(secret_key,msg) digest=h.digest() respone=conn.recv(len(digest)) return hmac.compare_digest(respone,digest) def data_handler(conn,bufsize=1024): if not conn_auth(conn): print(‘该链接不合法,关闭‘) conn.close() return print(‘链接合法,开始通信‘) while True: data=conn.recv(bufsize) if not data:break conn.sendall(data.upper()) def server_handler(ip_port,bufsize,backlog=5): ‘‘‘ 只处理链接 :param ip_port: :return: ‘‘‘ tcp_socket_server=socket(AF_INET,SOCK_STREAM) tcp_socket_server.bind(ip_port) tcp_socket_server.listen(backlog) while True: conn,addr=tcp_socket_server.accept() print(‘新连接[%s:%s]‘ %(addr[0],addr[1])) data_handler(conn,bufsize) if __name__ == ‘__main__‘: ip_port=(‘127.0.0.1‘,9999) bufsize=1024 server_handler(ip_port,bufsize)
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ from socket import * import hmac,os secret_key=b‘linhaifeng bang bang bang‘ def conn_auth(conn): ‘‘‘ 验证客户端到服务器的链接 :param conn: :return: ‘‘‘ msg=conn.recv(32) h=hmac.new(secret_key,msg) digest=h.digest() conn.sendall(digest) def client_handler(ip_port,bufsize=1024): tcp_socket_client=socket(AF_INET,SOCK_STREAM) tcp_socket_client.connect(ip_port) conn_auth(tcp_socket_client) while True: data=input(‘>>: ‘).strip() if not data:continue if data == ‘quit‘:break tcp_socket_client.sendall(data.encode(‘utf-8‘)) respone=tcp_socket_client.recv(bufsize) print(respone.decode(‘utf-8‘)) tcp_socket_client.close() if __name__ == ‘__main__‘: ip_port=(‘127.0.0.1‘,9999) bufsize=1024 client_handler(ip_port,bufsize)
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ from socket import * def client_handler(ip_port,bufsize=1024): tcp_socket_client=socket(AF_INET,SOCK_STREAM) tcp_socket_client.connect(ip_port) while True: data=input(‘>>: ‘).strip() if not data:continue if data == ‘quit‘:break tcp_socket_client.sendall(data.encode(‘utf-8‘)) respone=tcp_socket_client.recv(bufsize) print(respone.decode(‘utf-8‘)) tcp_socket_client.close() if __name__ == ‘__main__‘: ip_port=(‘127.0.0.1‘,9999) bufsize=1024 client_handler(ip_port,bufsize)
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ from socket import * import hmac,os secret_key=b‘linhaifeng bang bang bang1111‘ def conn_auth(conn): ‘‘‘ 验证客户端到服务器的链接 :param conn: :return: ‘‘‘ msg=conn.recv(32) h=hmac.new(secret_key,msg) digest=h.digest() conn.sendall(digest) def client_handler(ip_port,bufsize=1024): tcp_socket_client=socket(AF_INET,SOCK_STREAM) tcp_socket_client.connect(ip_port) conn_auth(tcp_socket_client) while True: data=input(‘>>: ‘).strip() if not data:continue if data == ‘quit‘:break tcp_socket_client.sendall(data.encode(‘utf-8‘)) respone=tcp_socket_client.recv(bufsize) print(respone.decode(‘utf-8‘)) tcp_socket_client.close() if __name__ == ‘__main__‘: ip_port=(‘127.0.0.1‘,9999) bufsize=1024 client_handler(ip_port,bufsize)
基于tcp的套接字,关键就是两个循环,一个链接循环,一个通信循环
socketserver模块中分两大类:server类(解决链接问题)和request类(解决通信问题)
server类:
request类:
继承关系:
以下述代码为例,分析socketserver源码:
ftpserver=socketserver.ThreadingTCPServer((‘127.0.0.1‘,8080),FtpServer)
ftpserver.serve_forever()
查找属性的顺序:ThreadingTCPServer->ThreadingMixIn->TCPServer->BaseServer
源码分析总结:
基于tcp的socketserver我们自己定义的类中的
基于udp的socketserver我们自己定义的类中的
import socketserver import struct import json import os class FtpServer(socketserver.BaseRequestHandler): coding=‘utf-8‘ server_dir=‘file_upload‘ max_packet_size=1024 BASE_DIR=os.path.dirname(os.path.abspath(__file__)) def handle(self): print(self.request) while True: data=self.request.recv(4) data_len=struct.unpack(‘i‘,data)[0] head_json=self.request.recv(data_len).decode(self.coding) head_dic=json.loads(head_json) # print(head_dic) cmd=head_dic[‘cmd‘] if hasattr(self,cmd): func=getattr(self,cmd) func(head_dic) def put(self,args): file_path = os.path.normpath(os.path.join( self.BASE_DIR, 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.request.recv(self.max_packet_size) f.write(recv_data) recv_size += len(recv_data) print(‘recvsize:%s filesize:%s‘ % (recv_size, filesize)) ftpserver=socketserver.ThreadingTCPServer((‘127.0.0.1‘,8080),FtpServer) ftpserver.serve_forever()
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()
标签:ons res encoding 执行 父类 roc 自己 encode 关系
原文地址:http://www.cnblogs.com/jingjing12/p/7710371.html