I. Overview
Python provides two levels of access to network services.
- The low-level network service supports the basic socket, which provides the standard BSD Sockets API to access all the methods of the underlying operating system socket interface.
- High-level Network Service Module Socketserver, which provides a server-centric class that simplifies the development of Web servers
Second, the parameters
- Family: The socket family can make Af_unix or af_inet
- Type: The socket type can be divided into either a connection-oriented or a non-connected
SOCK_STREAM
SOCK_DGRAM
- Protocol: General does not fill the default is 0.
Third, the service side
We use the socket function of the socket module to create a socket object. The socket object can set up a socket service by calling other functions.
We can now specify Port (port)of the service by invoking the bind (hostname) function.
Next, we call the accept method of the socket object. The method waits for the client to connect and returns a connection object that indicates that the client is connected.
The complete code is as follows:
1 #Coding=utf-82 #file name: server.py3 4 ImportSocket#Importing the Socket module5 6s = Socket.socket ()#creating a Socket object7Host = Socket.gethostname ()#get Local Host name8Port = 12345#Setting up Ports9S.bind ((host, Port))#Binding PortTen OneS.listen (5)#Waiting for client connections A whileTrue: -C, addr = S.accept ()#establish a client connection. - Print 'Address:', addr theC.send ('Welcome to! ') -C.close ()#Close Connection
Iv. Client
Next we write a simple client instance that connects to the service created above. The port number is 12345.
The socket.connect (hosname, Port) method opens a TCP connection to a service provider that hosts a port of hostname . After the connection we can start from the service end of the data, remember that the operation will need to close the connection after completion.
The complete code is as follows:
1 #Coding=utf-82 #file name: client.py3 4 ImportSocket#Importing the Socket module5 6s = Socket.socket ()#creating a Socket object7Host = Socket.gethostname ()#get Local Host name8Port = 12345#Set Port Good9 Ten S.connect ((host, port)) One PrintHost A Printsocket.gethostbyaddr (host) - Printsocket. SocketType - PrintS.RECV (1024) theS.close ()
Five. Python Internet module
Some important modules for Python network programming are listed below:
Protocol |
Functional Usefulness |
Port number |
Python Module |
HTTP |
Web Access |
80 |
Httplib, Urllib, Xmlrpclib |
NNTP |
Read and post news articles, commonly known as "posts" |
119 |
Nntplib |
Ftp |
File transfer |
20 |
Ftplib, Urllib |
Smtp |
Send mail |
25 |
Smtplib |
POP3 |
Receive mail |
110 |
Poplib |
IMAP4 |
Get Mail |
143 |
Imaplib |
Telnet |
Command line |
23 |
Telnetlib |
Gopher |
Information Lookup |
70 |
Gopherlib, Urllib |
Python Network programming