In Python, the socket module is used to encapsulate the various underlying communications, support the TCP/UDP protocol, and facilitate the programming of the C/S class.
The most common usage:
such as Ftp_server:
1 ImportSocketserver2 classMysocketserver (socketserver. Baserequesthandler):3 defhandle (self):4 whileTrue:5 Try:6SELF.DATA=SELF.REQUEST.RECV (1024). Strip ()7 Print(Self.client_address[0],'recv>>', Self.data)8 Self.request.send (Self.data.upper ())9 exceptException as E:Ten Print("the client is down! ", E) One Break AIpaddr='localhost' -port=9999 - #Server=socketserver. TCPServer ((ipaddr,port), mysocketserver) theServer=Socketserver. Threadingtcpserver ((ipaddr,port), mysocketserver) - Server.serve_forever () -Server.close_request ()Ftp_server_code
Ftp_client
1 ImportSocket2 3Client =Socket.socket ()4Client.connect (('localhost', 9999))5 whileTrue:6data = input (">>>>>>")7 ifLen (data) = = 0:Continue8Client.send (Data.encode ("Utf-8"))9Re_data = CLIENT.RECV (1024)Ten Print(Re_data) OneClient.close ()Ftp_client_code
The socket in Python