Python Basic Tutorial Summary 13--network Programming,

Source: Internet
Author: User
Tags http authentication ftp client

1. Network Design Module

1.1 Socket Module

depending on how the connection is started and the destination to which the local socket is connected, the connection between sockets can be divided into three steps: server Listening, client request, connection acknowledgement. 1) Server monitoring: Is the server end socket does not locate the specific client socket, but in the status of waiting for the connection, real-time monitoring network status. 2) Client request: Refers to the client's socket to make a connection request, to connect to the target is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket. 3) connection confirmation: Refers to when the server-side socket is heard or received a client socket connection request, it responds to the client socket request, set up a new thread, the server -side socket description to the client, once the client confirms the description, the connection is established. While the server-side socket continues to be in the listening state , it continues to receive connection requests from other client sockets.

One of the basic components in network programming is the socket (socket). Sockets are mainly "information channels" between two programs. Programs may be distributed across different computers (over a network connection), sending information to each other through sockets. Most of the network programming in Python hides the basic details of the socket module and does not directly interact with sockets.

Sockets consist of two: server sockets and client sockets . After creating a server socket, let it wait for the connection. This allows it to listen at a network address (the combination of an IP address and a port number). Processing a client socket is usually easier than processing a server socket because the server must be ready to handle the client's connection at any time, while processing multiple connections, while the client is simply a connection that completes the transaction and disconnects.

A socket is an instance of the socket class in a socket module. There are three parameters:

The first one is the address family (default is socket.af_inet);

The second argument is a stream ( the default is the socket.) Sock_stream, default value) or datagram (socket. SOCK_DGRAM) sockets;

The third parameter is the protocol used (default is 0, which is the default value). You do not need to provide any parameters for a common socket.

After the server-side socket uses the Bind method, the Listen method is called to listen for the given address. Client sockets connect to the server using the Connect method the address used in the Connect method is the same as the address in the bind method. In this case, an address is a tuple in the format (Host,port) where host is the hostname and port is the port number. The Listen method has only one parameter, which is the length of the connection that the server has not processed.

After the server socket starts listening, it can accept the client connection. This step is done using the Accept method. This method will block (wait) until the client connects, and then the method returns a tuple in the format (client,address) . The server can handle the client to its satisfaction, and then call an accept method to start waiting for the next connection. This process is usually implemented in an infinite loop.

Sockets have two methods: Send and Rev, which are used to transfer data. You can use a string parameter to call send to send data and call recv with a desired (maximum) number of bytes to receive the data. If you are not sure which number to use, then 1024 is a good choice.

1 #小型服务器2 Import Socket3s=Socket.socket ()4host=Socket.gethostname ()5port=12346 S.bind ((host,port))7S.listen (5)8  whileTrue:9C,ADDR =s.accept ()TenPrint"Got Connect from", addr OneC.send ('tkx for connecting') A c.close () -  -  the #小型客户端 -  - Import Socket -s=Socket.socket () +host=Socket.gethostname () -port=1234 + S.connect ((host,port)) APrint S.RECV (1024x768)

1.2 Urllib and URLLIB2 modules

Urllib and URLLIB2 are the most powerful features in the various network workspaces that can be used. They allow access to files over the network, just as those files exist on your computer. With a simple function call, you can use almost anything that the URL points to as input to the program. These two modules function the same, but the urllib is a little better. If you use just a simple download, urllib is enough. But Urllib2 is a good choice if you need to use HTTP authentication or cookies, or if you want to write extensions for your own protocols.

1) Open remote file

#打开远程文件 >>> from urllib import urlopen>>> webpage=urlopen ("http://blog.csdn.net/signjing")

The class file object returned by Urlopen supports the close, read, ReadLine, and ReadLines methods, and of course supports iterations.

2) Get remote files

The function Urlopen provides a class file object from which data can be read. If you want Urllib to download the file for you and have a copy of the file in your local file, you can use Urlretrieve.

Urlretrieve returns a tuple (filename,headers) instead of a class file object, filename is the name of the local file (created automatically by Urllib), and headers contains information about some remote files.

>>> Import urllib>>> urllib.urlretrieve (' http://www.baidu.com ', ' d:\\baidu.html ') (' d:\\ Baidu.html ', 

If you do not specify a filename, the file is placed in a temporary location, and you can open it with the open function. When you have completed the operation on it, you can delete it to save space, to delete the temporary file, you can use the Urlcleanup function, do not need to provide parameters.

1.3 Other modules

Module

Describe

Asynchat

Enhanced version of Asyncore

Asyncore

Asynchronous sockets Handler

Cgi

Basic CGI Support

Cookies

Cookie object manipulation, primarily for servers

Cookielib

Client cookie Support

Email

Email message Support

Ftplib

FTP client Module

Gopherlib

Gopher Client Module

Httplib

HTTP Client Module

Imaplib

IMAP4 Client Module

Mailbox

Read the format of several mailboxes

Mailcap

Accessing MIME configuration via Mailcap file

Mhlib

Visit MH Mailbox

Nntplib

NNTP Client Module

Poplib

Pop client Module

Robotparser

Support for parsing Web server robot files

Simplexmlrpcserver

A simple XML-RPC server

Smtpd

SMTP server-side modules

Smtplib

SMTP Client Module

Telnetlib

Telnet Client Module

Urlparse

Support for interpreting URLs

Xmlrpclib

Client Support for XML-RPC

2. Socketserver

The Socketserver module is the basis for many server frameworks in the standard library. Socketserver contains 4 basic classes: TCPServer for TCP sockets, Udpserver for UDP datagram sockets, and Unixstreamserver and unixdatagramserver for non-targeted.

3. Multi-Connection

The server solutions that have been discussed so far are synchronous: a single client can be connected at a time and requests to process it. How do you handle multiple connections at the same time?

Three methods: Fork (forking), Thread (threading), and asynchronous I/O (asynchronous I/O).

4. Twisted

Twisted is an event-driven Python network framework that was originally developed for online games and is now used by all types of Web software.

Python Basic Tutorial Summary 13--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.