A .TCP upload large files
Server-side
import socket import json import struct server = socket.socket() server.bind(('127.0.0.1',8080)) server.listen(5) while True : conn,addr = server.accept() while True: try: header = conn.recv(4) dict_size = struct.unpack('i',header)[0] dic_byte = conn.recv(dict_size) dic = json.loads(dic_byte.decode('utf-8')) file_size = dic.get('file_size') recv_size = 0 with open(dic.get('file_name'),'wb') as f : while recv_size <file_size : data = conn.recv(1024) f.write(data) recv_size += len(data) print('#####******####') print('上传成功') except ConnectionResetError : break conn.close()
Client-side
import socket import json import struct import os client = socket.socket() client.connect(('127.0.0.1',8080)) while True : MOVIE_DIR = r'D:\笔记\film' movie_list = os.listdir(MOVIE_DIR) for index,movie in enumerate(movie_list,1) : print(index,movie) choice = input(">> : ").strip() if choice.isdigit(): choice = int(choice)-1 if choice >= 0 and choice <len(movie_list) : file_name = movie_list[choice] file_path = os.path.join(MOVIE_DIR,file_name) file_size = os.path.getsize(file_path) d = { 'file_name' : file_name, 'file_size' : file_size, 'info' : '高清无码' } json_d = json.dumps(d) dic_byte = json_d.encode('utf-8') header = struct.pack('i',len(dic_byte)) client.send(header) client.send(dic_byte) with open(file_path,'rb') as f : for line in f : client.send(line) else: print('out of range') else: print('not is digit')
II. The exception mechanism
Exception: the program is running error occurred unpredictable, there is no corresponding processing mechanism for processing,
Program will be interrupted, throw an exception.
Structural abnormalities:
Exception Type
Abnormal information
Abnormal position
Abnormal type:
Grammatical errors
logical error
The exception thrown way:
Run error passive thrown
Use exception type (abnormality information) raise, take the initiative to throw
Exception handling:
the try : L = [l, 2,3 ] L [ 111 ] # Exception are universal and abnormal BaseException # wherein BaseException is Exception the except BaseException: # universal exception all exception types are captured Print ( ' 6666 ' )
Use with other match:
else: to try: ...... except in conjunction, the program does not throw an exception will be executed
finally: to try: ...... except in conjunction with or without an exception will be executed
Assert assert: guess a state data, wrong as AssertionError throw an exception. Guessed it, the code normal execution
Custom exception:
class MyError (BaseException): DEF __init__ (Self, msg): Super (). __init__ () self.msg = msg DEF __str__ (Self): return ' <dfsdf% ssdfsdaf> ' % self.msg The raise MyError ( ' myself defined exceptions ' )
The difference between the UDP and three .TCP
TCP(Transmission Control Protocol):
We will stick package
You can not send space
The case of the server does not exist, the client will get an error
Does not support concurrent
UDP(User Datagram Protocol):
Comes header, will not stick package
Supports sending space
The case of the server does not exist, the client will not be given
Support concurrent
Run a real sense at the same time: parallel; looks like running simultaneously: PS: Concurrency
The basic four-.UDP
Server
Import Socket Server = socket.socket (type = socket.SOCK_DGRAM) # the UDP protocol server.bind (( ' 127.0.0.1 ' , 8080 )) # the UDP connection pool it is unnecessary to provide the half no concept of semi-connection pool # because there is no bidirectional communication channel is no direct circulation Accept the while True: data, addr = server.recvfrom (1024 ) Print ( ' data: ' , data) # client message sent by the Print ( ' address: ' , addr) # client address server.sendto (data.upper (), addr)
Client
Import Socket Client = socket.socket (type = socket.SOCK_DGRAM) # without establishing a connection directly to the communication cycle the server_address = ( ' 127.0.0.1 ' , 8080 ) the while True: client.sendto (B ' Hello ' , the server_address) Data, addr = client.recvfrom (1024 ) Print ( ' service data sent by the end ' , data) Print ( ' server address ' , addr)
五.SocketServer
TCP server
Import SocketServer class MyServer (of SocketServer.BaseRequestHandler): DEF handle (Self): # print ( 'coming brother') the while True: Data = self.request.recv (1024 ) Print (self.client_address) # client address Print ( data.decode ( ' UTF-. 8 ' )) self.request.send (data.upper ()) IF the __name__ == ' __main__ ' : "" " a client is connected automatically to the method defined from the handle class to deal with "" " ServerSocketserver.ThreadingTCPServer = (( ' 127.0.0.1 ' , 8080), MyServer) # Create a TCP-based Object () server.serve_forever # start the service object
TCP Client
import socket client = socket.socket() client.connect(('127.0.0.1',8080)) while True: client.send(b'hello') data = client.recv(1024) print(data.decode('utf-8'))
UDP client
Import SocketServer class MyServer (of SocketServer.BaseRequestHandler): DEF handle (Self): # Print ( 'coming brother') the while True: Data, our sock = self.request Print (self.client_address) # client address Print (data.decode ( ' UTF-. 8 ' )) sock.sendto (data.upper (), self.client_address) IF the __name__ == ' __main__ ' : "" " a client is connected automatically to the method defined from the handle to the class treatment "" " ServerSocketserver.ThreadingUDPServer = (( ' 127.0.0.1 ' , 8080), MyServer) # Create a TCP-based Object () server.serve_forever # start the service object
UDP server
import socket import time client = socket.socket(type=socket.SOCK_DGRAM) server_address = ('127.0.0.1',8080) while True: client.sendto(b'hello',server_address) data,addr = client.recvfrom(1024) print(data.decode('utf-8'),addr) time.sleep(1)