1, the socket of the basic TCP/IP protocol is the host access to the Internet and access to the Internet interconnection between the two host communication interconnection standard physical layer: the transmission of the binary link layer: The binary number is grouped, the only one host data frame: Header: 18 bytes of the original address , Destination address, data type, data: Up to 1500 bytes Network layer: Run IP protocol, can allow each subnet to communicate between the two host IP address Transport layer: TCP/TDP, marking port number: Application Session Layer: Presentation Layer Application Layer
Soctet: Is the encapsulation of the TCP/IP protocolThe socket is simply processing the data to be sent, or the TCP,UDP protocol behind the actual transmission. 2. Socket usage
As an example:
Buy mobile phone s= socket.socket () Binding: Power On: S.listen (5) Waiting for phone: conn,addr = s.accept () Conn: is the line of communication between a server and a specific client addr: Client address Receive Message Recv_ data = CONN.RECV (1024) Send Message Send_data = Recv_data.upper () conn.send (Send_data)
Attention:
2.7 can send string 3.0 to be sent after the bitstream server: Do not specify the character encoding, because the client sends a bit stream, so the client returns a bit stream
3, socket multi-threaded use
ImportSocketserverImportsubprocessclassMyServer (socketserver. Baserequesthandler):defhandle (self):#Print Self.request,self.client_address,self.serverSelf.request.sendall (Bytes ('Welcome to call 10086, please input 1xxx,0 to manual service.', encoding="Utf-8")) whileTrue:data= SELF.REQUEST.RECV (1024) ifLen (data) = = 0: Break Print("[%s] says:%s"%(Self.client_address,data.decode ()))#Self.request.sendall (Data.upper ())cmd = subprocess. Popen (Data.decode (), shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) Cmd_res=Cmd.stdout.read ()if notCmd_res:cmd_res=Cmd.stderr.read ()ifLen (cmd_res) = = 0:#cmd have not outputCmd_res = Bytes ("cmd has output", encoding="Utf-8") self.request.send (cmd_res)
Socket Multithreading
Python_way, Day9 socket and soctet multi-threaded usage