VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • python基础(30):黏包、socket的其他方法(6)

  • """
  • 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
  • client:

    
    	
    1. import socket
    2. import struct
    3. import json
    4. import os
    5.  
    6. class MYTCPClient:
    7. address_family = socket.AF_INET
    8.  
    9. socket_type = socket.SOCK_STREAM
    10.  
    11. allow_reuse_address = False
    12.  
    13. max_packet_size = 8192
    14.  
    15. coding='utf-8'
    16.  
    17. request_queue_size = 5
    18.  
    19. def __init__(self, server_address, connect=True):
    20. self.server_address=server_address
    21. self.socket = socket.socket(self.address_family,
    
    相关教程