Python Network programming Beginner

Source: Internet
Author: User

Network programming patents should belong to UNIX, each platform (such as Windows, Linux, etc.), the language (c, C + +, Python, Java, etc.) to achieve the same characteristics of the syntax are similar. In my opinion, understand the UNIX socket network programming, other forms of network programming method also know. This sentence is not very rigorous. Accurate should be said to understand the principle of socket programming, network programming also know, the difference lies in each platform, each language has its own exclusive grammar, we directly flexible to apply on the line.

The following is an example of the most basic network programming implemented in Python, which is a one-way "data flow" between the client and the server, relying on the client-server architecture. We do it in two ways, one is the most primitive socket programming, and the other is to encapsulate the first method with Python's object-oriented approach, with the goal of reducing transparency and enabling rapid development.

Requirements: Client input data, sent to the server side, servers generated (timestamp + data) encapsulated data response to the client. Since socket programming consists of two types: connection-oriented and non-connected, these two correspond to TCP data streams and UDP data packets respectively. Therefore, both of our methods are implemented.

One, Python socket programming

Connection-oriented TCP socket programming:

1 #-*-coding:utf-8-*-23  fromSocketImport*4  fromTimeImportCTime5 6 #Address and Port7HOST ="'8PORT = 215679ADDR =(HOST, PORT)Ten  One #buffsize ABufsiz = 1024 -  - #Build Socket theTcpsersock =socket (af_inet, sock_stream) - #bind socket - Tcpsersock.bind (ADDR) - #Listen 5 Client +Tcpsersock.listen (5) -  + Try: A      whileTrue: at         Print 'waiting for connection ...' -         #Build Client Socket -Tcpclisock, addr =tcpsersock.accept () -         Print '... connect from:', addr -  -         #accept data and process in          whileTrue: -data =tcpclisock.recv (Bufsiz) to             if  notData: +                  Break -Tcpclisock.send ('[%s]%s'%(CTime (), data)) the  *             #Close Client Socket $ tcpclisock.close ()Panax Notoginseng exceptEoferror, Keyboardinterrupt: -Tcpsersock.close ()
1 #-*-coding:utf-8-*-2 3  fromSocketImport*4 5 #Address and Port6HOST ='127.0.0.1'7PORT = 215678ADDR =(HOST, PORT)9 Ten #buffersize OneBufsiz = 1024 A  - #Build Socket -Tcpclisocket =socket (af_inet, sock_stream) the Tcpclisocket.connect (ADDR) -  -  whileTrue: -data = Raw_input ('>') +     if  notData: -          Break +     #Send Data A tcpclisocket.send (data) at     #recv Data -data =tcpclisocket.recv (Bufsiz) -     if  notData: -          Break -     #Show Data -     PrintData inTcpclisocket.close ()

Non-connected UDP socket programming

1 #-*-coding:utf-8-*-2 3  fromSocketImport*4  fromTimeImportCTime5 6 #Address and Port7HOST ="'8PORT = 80009ADDR =(HOST, PORT)Ten  One #buffersize ABuffsize = 1024 - #Build Socket -Udpsersock =socket (af_inet, SOCK_DGRAM) the #bind socket - Udpsersock.bind (ADDR) -  - Try: +      whileTrue: -         Print 'waiting the message ...' +data, addr =Udpsersock.recvfrom (buffsize) A         Print 'received the message:'+data+'From :', addr atUdpsersock.sendto ('[%s]%s'%(CTime (), data), addr) - exceptEoferror, Keyboardinterrupt: -Udpsersock.close ()
1 #-*-coding:utf-8-*-2 3  fromSocketImport*4 5 #Address and Port6HOST ='localhost'7PORT = 80008ADDR =(HOST, PORT)9 Ten #buffersize OneBufsiz = 1024 A  - #Build Socket -Udpclisock =socket (af_inet, SOCK_DGRAM) the  -  whileTrue: -data = Raw_input ('>') - udpclisock.sendto (data, ADDR) +data =Udpclisock.recvfrom (Bufsiz) -     if  notData: +          Break A     PrintData atUdpclisock.close ()

Second, the network programming based on encapsulation class Socketserver

1 #-*-coding:utf-8-*-2 3  fromSocketserverImportTCPServer as TCP, Streamrequesthandler as SRH4  fromTimeImportCTime5 6 #Address and Port7HOST ="'8PORT = 215679ADDR =(HOST, PORT)Ten  One #buffsize ABufsiz = 1024 -  - #Build RequestHandler the classMyrequesthandler (SRH): -     defhandle (self): -         Print '... connected from:', Self.client_address -Self.wfile.write ('[%s]%s'%(CTime (), Self.rfile.readline ())) +  - #Build TCPServer +Tcpserv =TCP (ADDR, Myrequesthandler) A Print 'waiting for connection ...' at #Loop to process -Tcpserv.serve_forever ()
1 #-*-coding:utf-8-*-2 3  fromSocketImport*4 5 #Address and Port6HOST ='127.0.0.1'7PORT = 215678ADDR =(HOST, PORT)9 Ten #buffersize OneBufsiz = 1024 A  -  whileTrue: -     #The default behavior of the Note:socketserver request processor is to accept the connection, the     #get the request and then close the connection, so multiple connections are required -Tcpclisock =socket (af_inet, sock_stream) - Tcpclisock.connect (ADDR) -  +     #Process Data -data = Raw_input ('>') +     if  notData: A          Break atTcpclisock.send ('%s\r\n'%data) -  -data =tcpclisock.recv (Bufsiz) -     if  notData: -          Break -     PrintData.strip () inTcpclisock.close ()

Python Network programming Beginner

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.