Python Network programming

Source: Internet
Author: User

This post is a note in the 16th chapter of Python core programming

This paper mainly introduces the use of this low-level protocol based on socket, because it is the bottom layer, so it is very useful to tune bugs in God Horse.

A few examples of customers and servers:

Hardware: Printer server, File server

Software forms: Web server, Database server, Window server

About the bank teller, too. A client server model like this

About sockets

Sockets are the lowest level of network communication.

The two categories of sockets are:

Af_unix (for local) and af_inet (for network)

Python only supports Af_unix,af_netlink, and the Af_inet family. Since we only care about network programming,
Most of the time, we use only af_inet

Address and Port

If the socket is compared to the socket of the telephone-the lowest structure of the communication, the host and port are like the area code and the telephone number.
A pair of combinations. It's not enough to have the hardware to call, you need to know who you want to call and where to hit.

Another way to classify sockets:

Connection oriented

The primary protocol for implementing this connection is the Transmission Control Protocol (TCP). To create a TCP socket, you have to create the
Specifies that the socket type is sock_stream. The TCP socket uses the name Sock_stream, which expresses it as a stream socket.
Characteristics. Because these sockets use Internet Protocol (IP) to find hosts in the network, the entire system is formed, generally
is referred to by both protocols (TCP and IP) , TCP/IP.

No connection

The primary protocol for implementing this connection is the User Datagram Protocol (that is, UDP). To create a UDP socket, you have to create a
Specifies that the socket type is SOCK_DGRAM. Sock_dgram the name, perhaps you have guessed, from the word "datagram"
("Datagram"). Because these sockets use Internet protocols to find the hosts in the network, the entire system is formed, a
these two protocols (UDP and IP) are referred to as UDP/IP.

Sockets in Python

Using the Socket module

How to use this module you can Google or view Help (socket)

Using it is done by creating a socket object, and then all the actions are implemented by means of the object, and the socket object Construction Amount parameter is the above concept.

Using the Socket Development server

You may want to know how many software servers are developed, since the socket is the underlying network programming components, then you can use it to develop a Web server, the following code using the socket module to achieve a simple time server, using TCP/IP, Examples of using UDP can refer to the original book

Service-Side code:

     ImportSocket fromTimeImportCTime#Create a Socket objectSock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#bind this socket object to a server address, here is the localSock.bind (('localhost', 8001))      ##设置好套接字开始监听, what does the 5 mean?Sock.listen (5)      #start a loop of infinite waiting services     whileTrue:Print 'Waiting for connection .'        ##当用户请求时, create a socket for the user, and the address of the userCliensock,address =sock.accept ()PrintCliensockPrint 'Conncet from', AddressTry:              ##设置客户请求的等待时间Cliensock.settimeout (5)              ## Accept the customer's request, data is the returned information, as if the example is of type stringdata = CLIENSOCK.RECV (1024)                ##返回一个字符类型的数据, use the Send methodCliensock.send ('[%s]%s'%(CTime (), data))exceptsocket.timeout:Print ' Time Out'cliensock.close ()

Client code

    ImportSocket#creating a Socket objectSock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#link to a server addressSock.connect (('localhost', 8001))     #send data, string of typeSock.send ('Fvsbvdb')     #accept the returned data    PrintSOCK.RECV (1024) Sock.close ()

An enhanced socket module?

Socketserver is a high-level module in the standard library. Used to simplify the implementation of network clients and servers. module,
Some classes have been implemented that are available for use.

You will also notice that our program is now "event driven". This means that the program has a "reaction" only when the event occurs. Interface Programming (chapter 18th) is also event-driven. You will notice a similarity in that the last line of code has an infinite loop of the server waiting for and processing the customer's service request.

Please take a closer look at the following code to implement the above time server, you will find this become object-oriented programming and event-driven

Server Segment Code

 fromSocketserverImportTCPServer as tcp,streamrequesthandler as SRH fromTimeImportCtimehost="'PORT= 21567ADDR=(HOST, PORT)classMyrequesthandler (SRH):defhandle (self):Print '... connected from:', self.client_address self.wfile.write ('[%s]%s'%(CTime (), Self.rfile.readline ())) Tcpserv=TCP (ADDR, Myrequesthandler)Print 'waiting for connection ...'Tcpserv.serve_forever ()

Client code

 fromSocketImport*HOST='localhost'PORT= 21567Bufsiz= 1024ADDR=(HOST, PORT) whileTrue:tcpclisock=socket (af_inet, Sock_stream) tcpclisock.connect (ADDR) data= Raw_input ('>')    if  notData: BreakTcpclisock.send ('%s\r\n'%data) Data=tcpclisock.recv (Bufsiz)if  notData: Break    PrintData.strip () tcpclisock.close ( )

Twisted frame???

Twisted is a fully event-driven network framework. It allows you to use and develop fully asynchronous network applications and protocols.

It provides a great help for you to create a complete system. System can be: network protocol, thread, security and authentication, chat/Instant Messaging, database management, relational database integration, Web/Internet, e-mail, command line parameters, graphical interface integration and so on.

Python modules related to network and sockets

Socket underlying network interface.
Asyncore/provides the underlying functionality for network applications that can handle client requests asynchronously.
Asynchat
Select manages multiple socket connections in a single-threaded network server program.
The socketserver contains the high-level modules required to write Web application servers. Complete processes and threads are provided
The version.

Suggestions

The async* and Socketserver modules provide a high level of functionality in creating servers. Because it is based on the socket and
(or) Select module, which encapsulates all the underlying code, which allows you to quickly develop a client/server system .

Although async* is the only asynchronous development support library provided by the standard library. We can also choose the relative twisted such as
A more modern, more powerful third-party library of quasi-Libraries.

The topics we discuss in this chapter cover programming with the socket network in Python and how to use low-level protocols such as TCP/IP
and UDP/IP to create the application . If you want to develop high-level web and Internet applications , we strongly recommend that you
Read Chapters 17th and 20th.

Chapters 17th and 20th are: Network client programming and Web programming

Extra: Explanation of synchronous asynchronous for blocking non-blocking

Python Network programming

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.