Dynamic import of modules
Assertion
Socket Server
I. Dynamic import of modules
1 class C (object): 2 def __init__ (self): 3 " Zhangsan "
1 # Dynamic Import 2 Import importlib3 test = Importlib.import_module ("lib.test") 4print(test. C (). Name)
Second, assert
Assert assertion is a sentence that must be equivalent to a Boolean true judgment!
1 is not equal to 0, there will be assertionerror anomalies.
1 equals 0, no exception.
If the assertion succeeds (if true) then no action is taken!
If the assertion is unsuccessful, the assertionerror is triggered
Try : assert True = = 0except assertionerror as e :print(" Assertion not valid " )else: print(" assertion established " )>>> Assertion not established
1 Try:2 assertTrue = = 13 exceptAssertionerror as E:4 Print("Assertion not established")5 Else:6 Print("Assertion established")7>>> Assertion established
Third, Socket Server
Socket Families (address cluster)
socket.
AF_UNIX unix本机进程间通信
socket.
AF_INET IPV4
socket.
AF_INET6 IPV6
Socket Types
socket.
SOCK_STREAM #for tcp
socket.
SOCK_DGRAM #for udp
socket.
SOCK_RAW #原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
socket.
SOCK_RDM #是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
socket.
SOCK_SEQPACKET #废弃了
Socket method
Sk.bind (Address)
S.bind binds the socket to the address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port).
Sk.listen (Backlog)
Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected.
The backlog equals 5, indicating that the kernel has received a connection request, but the server has not yet called the accept to process the maximum number of connections is 5
This value cannot be infinitely large because the connection queue is maintained in the kernel
Sk.setblocking (BOOL)
Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.
Sk.accept ()
Accepts the connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.
Incoming TCP Client connection (blocked) waiting for connection
Sk.connect (Address)
The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.
SK.CONNECT_EX (Address)
Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061
Sk.close ()
Close socket
SK.RECV (Bufsize[,flag])
Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.
Sk.recvfrom (Bufsize[.flag])
Similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
Sk.send (String[,flag])
Sends data from a string to a connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string. That is, the specified content may not be sent all.
Sk.sendall (String[,flag])
Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
Internally, the send is called recursively, sending all the content.
Sk.sendto (string[,flag],address)
Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.
Sk.settimeout (Timeout)
Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as client connections waiting up to 5s)
Sk.getpeername ()
Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
Sk.getsockname ()
Returns the socket's own address. Typically a tuple (ipaddr,port)
Sk.fileno ()
File descriptor for sockets
socket.
sendfile
(file, offset=0, count=none)
Send the file.
Server-side
ImportSocketserverclassMytcphandler (socketserver. Baserequesthandler):defhandle (self): whileTrue:Try: Self.data= SELF.REQUEST.RECV (1024). Strip ()Print("{} wrote:". Format (Self.client_address[0]))Print(Self.data) self.request.send (Self.data.upper ())exceptConnectionreseterror as E:Print("Error", E) Breakif __name__=='__main__': Host,port="localhost", 9999Server=Socketserver. Threadingtcpserver ((host,port), Mytcphandler) Server.serve_forever ()
#ClientImportsocketclient= Socket.socket ()#declares the socket type and generates the socket connection object at the same time#Client.connect ((' 192.168.16.200 ', 9999))Client.connect (('localhost', 9999)) whiletrue:msg= Input (">>:"). Strip ()ifLen (msg) = = 0:Continueclient.send (Msg.encode ("Utf-8")) Data= Client.recv (10240) Print("recv:", Data.decode ()) Client.close ()
#FTP Service SideImportOs,hashlibImportSocketserver=socket.socket () Server.bind ('localhost', 9999) ) Server.listen () whiletrue:conn,addr=server.accept ()Print("New Conn:", addr) whileTrue:Print("waiting for new instructions") Data= CONN.RECV (1024) if notData:Print("client has been disconnected") BreakCmd,filename=Data.decode (). Split ()Print(filename)ifos.path.isfile (filename): F= open (filename,"RB") M=hashlib.md5 () file_size=os.stat (filename). st_size conn.send (str (file_size). Encode ()) Conn.recv (1024) forLineinchf:m.update (line) conn.send (line)Print("file MD5", M.hexdigest ()) F.close () Conn.send (M.hexdigest (). Encode ())Print("Send Done") Server.close ()
#FTP clientImportsocket,hashlibclient=socket.socket () Client.connect ("localhost", 9999)) whileTrue:cmd= Input (">>:"). Strip ()ifLen (cmd) = = 0:Continue ifCmd.startswith ("Get"): Client.send (Cmd.encode ()) Server_response= CLIENT.RECV (1024) Print("Server response:", Server_response) client.send (b"Ready to recv file") File_total_size=Int (Server_response.decode ()) Received_size=0 filename= Cmd.split () [1] F= Open (filename+". New","WB") M=hashlib.md5 () whileReceived_size <file_total_size:ifFile_total_size-received_size > 1024:#to receive more than onceSize = 1024Else:##最后一次了, how much is left ?Size = File_total_size-received_sizePrint("Last receive:", size) data=client.recv (size) received_size+=len (data) m.update (data) f.write ( data)Else: New_file_md5=m.hexdigest ()Print("file recv done", Received_size,file_total_size) f.close () server_file_md5= CLIENT.RECV (1024) Print("Server file MD5", SERVER_FILE_MD5)Print("Client file MD5", NEW_FILE_MD5) client.close ()
Python path-python (object-oriented advanced (module dynamic import, assertion, Socket Server))