2, upload movie, udp, exception handling, socketserver

Today, content 
1, operation: to achieve the user to upload the movie loop
2, exception processing
3, UDP communication
. 4, the SocketServer
1, job:
Client:
Import OS
Import struct
Import Socket
Import JSON


Client socket.socket = ()
the client.connect (( ' 127.0.0.1 ", 1688))

the while True:
# get the absolute file path
MOVIE_PATH = r'D: \ preview video \ day12 \ video '
# get movie listings directory
movie_list = os.listdir (MOVIE_PATH)
# loop to print a list of movies
for i, movie in enumerate (movie_list) :
Print (i, Movie)
# allow the user to select a movie numbered list
choice = input ( 'Please enter the article number:') Strip ().
IF choice.isdigit ():
Choice = int (Choice)
IF Choice in the Range (0, len (movie_list)):
# get the user to select the movie path
path = movie_list [choice]
# absolute path splicing film
path_dir = os.path.join (MOVIE_PATH, path)
# get the file size
file_size = os.path.getsize (path_dir)
# create a dictionary
d = { 'name': 'Love your life Qian Baihui .mp4', 'file_size': file_size , 'ps':' drink do not drive! '}
# Serialize the dictionary
json_dict = json.dumps (D)
# serialized string into binary data
dict_bytes = json_dict.encode (' UTF-. 8 ')
# create a dictionary header
header = struct.pack ( 'I', len (dict_bytes))
# send dictionary header
client.send (header)
# send dictionary
client.send (dict_bytes)
# file transmission cycle data transactions
with open (path_dir,
Line F in for:
client.send (Line)
the else:
Print ( "choose not within the scope ')
the else:
Print ('! by the number ')
server:
Import struct
Import Socket
Import JSON

Server socket.socket = ()
server.bind (( '127.0.0.1', 1688))
server.listen (. 5)

the while True:
Conn, addr = server.accept ()
the while True:
the try:
# Receiving a predetermined message length
header_len conn.recv = (. 4)
# dictionary to parse the headers
header_len struct.unpack = ( 'I', header_len) [0]
# accepted dictionary
header_dict = conn.recv (header_len)
# to receive deserialize the data into binary format json dictionary
dict_json = json.loads (header_dict.decode ( 'UTF-. 8'))
# acquired from the dictionary file size
FILE_SIZE = dict_json.get ( 'FILE_SIZE')
# receiving cycle and writing files
= 0 recv_size
# is available here is the dictionary name
Open with (dict_json.get ( 'name'), 'WB') AS F:
the while recv_size <FILE_SIZE:
Data = conn.recv (1024)
# read out 1024 bytes of data that will be written to the file
f.write (data)
# until all data written to the file data is accepted finished ******************
recv_size + = len (data)
the except ConnectionResetError aS E:
Print (E)
BREAK
conn.Close ()

2: Exception handling
What is an exception?
program unpredictable error occurred during operation
And the error is no corresponding processing mechanism, it will be shown in an abnormal form of
the impact of the whole program is no longer running

structural abnormalities
1. The type of exception: NameError
2. abnormal information: name 'fdsdfsdf' is not defined
3. abnormality location: Traceback (MOST Recent Last Call):
File "D: / Python 10 full-time video / day29 / 01 exception handling .py", Line. 1, in <Module1>
fdsdfsdf

types of abnormalities
are divided into two class
1. syntax errors
are immediately able to solve your program, this error can not be tolerated
after grammatical errors discovered should be immediately resolved

2. logical errors ****
this error can be tolerated because a glance not out
For logical error exception handling mechanism can be used to capture, with the try, the except
PS: the except followed the wrong type

common type of error
NAMERROR name wrong **********
SyntaxError Syntax error ****** ****
a KeyError key ********** absent
ValueError error value **********
IndexError index errors **********
the try:
name
L = [ l, 2,3]
L [111]
D = { 'name': 'Jason'}
D [ 'password']
the except NameError:
Print ( 'NameError')
IndexError the except:
Print ( 'IndexError')
the except KeyError:
Print ( 'KeyError')

PS: 1, after an error occurs, it will immediately stop running the code,
2, will take the first except, as long as the error. The following will not go except
3, except BaseException: # universal abnormal all exception types are captured
Exception is universal abnormal, he inherited BaseException
how to avoid
exception handling
when you think of the code block above the bug may occur try this: Note inner try block as possible *****

try:
possibility of error codes
except the type of error as e: # the error message assigned to the variable e
processing mechanism after error ========== ======================




the try:
# name
= L [l, 2,3]
L [111]
# D = { 'name': 'Jason'}
# D [ 'password']
the except Exception: # universal exception all exception types are captured
print ( 'world I invincible ')
the else:
Print (' code is detected without any exception will go the else ')
a finally:
Print (' whether the detected code has no exception will be executed after the code has finished running


the initiative to throw an exception
if 'egon '==' DSB ':
Pass
the else:
raise TypeError (' do say a big truth ')
keyword raise is actively thrown


L = [, 2, 3]
the Assert len (L) <0 # assertion prophecy
guess the state of a data guessed it does not affect the normal travel time code execution
Direct wrong error

L = [, 2, 3]
the Assert len (L) <0 # assertion prophecy
guess some state data guessed it does not affect the normal code execution go
wrong as a direct error

custom exception
9 Custom exception
class MyError with the (BaseException):
DEF the __init __ (Self, MSG):
Super () __ .__ the init ()
self.msg MSG =
DEF __str __ (Self):
return '<dfsdf% ssdfsdaf>'% self.msg

The raise MyError with the ( 'I abnormal own definition of ') # initiative is actually an object thrown exception classes


3, UDP protocol
1, udp packet will not stick, because he is a datagram protocol, comes header
2, you do not need to link directly to send data, there is no two-way channel, just send a text message as
3, when the server does not exist, it does not complain client allows empty hair

Client:
Import Socket

Client = socket.socket (type = socket.SOCK_DGRAM)

The server_addr = ( '127.0.0.1', 1688)
the while True:
client.sendto (b'fggfgfghyhjh ', The server_addr)
Data, client.recvfrom addr = ( 1024)
Print ( 'data sent by the server', data)
Print ( 'server address', addr)
server:
Import Socket

Server = socket.socket (type = socket.SOCK_DGRAM)
server.bind ((' 127.0. 0.1 ', 1688))
# necessary to provide half UDP connection pool, the pool does not link the concept
# no bidirectional channel, it is not necessary accept, direct communication cycle
while True:
data, addr = server.recvfrom (1024) accepts data
print ( 'data', data) # client to the data
print (addr) # ip address of the client and the port
server.sendto (data.lower (), addr) send data and address data #

simple version of qq case:
server:
Import socket

Server = socket.socket (of the type = socket.SOCK_DGRAM)
server.bind (( '127.0.0.1', 1688))

the while True:
the data, addr = server.recvfrom (1024)
Print (data.decode ( 'UTF-. 8'))
MSG = INPUT ( '>>>>:')
server.sendto (msg.encode ( 'UTF-. 8'),addr)

Client:
Socket Import
Client = socket.socket (type = socket.SOCK_DGRAM)
The server_addr = ( '127.0.0.1', 1688)

the while True:
MSG = INPUT ( '>>>>:')
MSG = '0 data from the client terminal: S% '% MSG
client.sendto (msg.encode (' UTF-. 8 '), The server_addr)
Data, addr = client.recvfrom (1024)
Print (data.decode (' UTF-. 8 '))

. 4, the SocketServer (so tcp supports concurrent, also supports UDP)
client:
Import Socket

client socket.socket = ()
the client.connect (( '127.0.0.1', 8080))

the while True:
client.send(b'hello')
data = client.recv(1024)
print(data.decode('utf-8'))
服务端:
import socketserver

class MyServer(socketserver.BaseRequestHandler):
def handle(self):
while True:
data = self.request.recv(1024)
print(self.client_address)
print(data.decode('utf-8'))
self.request.send(data.upper())


if __name__ == '__main__':
# 创建一个tcp对象
server = socketserver.ThreadingTCPServer(('127.0.0.1',1688),MyServer)
server.serve_forever()

Guess you like

Origin www.cnblogs.com/Fzhiyuan/p/11324179.html