Note: The source novice tutorial, if there is infringement, notice, the legislative deletion
Python Network Programming
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.
The high-level Network Service module, Socketserver, provides a server-centric class that simplifies the development of network servers.
What is a Socket?
A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.
Socket () function
In Python, we use the socket () function to create a socket with the following syntax:
socket.socket([family[, type[, proto]]])
Parameters |
Description |
Family |
The socket family can make Af_unix or af_inet |
Type |
Socket types can be divided into sock_stream or sock_dgram depending on whether they are connection-oriented or non-connected |
Protocol |
The default is 0 for general non-fill. |
Socket object (built-in) method
Parameters |
Description |
Server-side sockets |
|
S.bind () |
The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port). |
S.listen () |
Start TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5. |
S.accept () |
Passively accepts TCP client connections, (blocking) waits for a connection to arrive |
Client sockets |
|
S.connect () |
Actively initializing the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection. |
S.CONNECT_EX () |
Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs |
Socket functions for public use |
|
S.RECV () |
Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. |
S.send () |
Sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string. |
S.sendall () |
Complete sending of TCP data, complete sending of TCP data. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception. |
S.recvform () |
The UDP data is received, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data. |
S.sendto () |
Sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent. |
S.close () |
Close socket |
S.getpeername () |
Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port). |
S.getsockname () |
Returns the socket's own address. Typically a tuple (ipaddr,port) |
S.setsockopt (Level,optname,value) |
Sets the value of the given socket option. |
S.getsockopt (Level,optname[.buflen]) |
Returns the value of the socket option. |
S.settimeout (Timeout) |
Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ()) |
S.gettimeout () |
Returns the value of the current timeout, in seconds, or none if the timeout period is not set. |
S.fileno () |
Returns the file descriptor for the socket. |
S.setblocking (flag) |
If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised. |
S.makefile () |
Create a file associated with the socket |
Simple example
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:
#!/usr/bin/python#-*-Coding:utf-8-*-# file name: server.pyImportSocket # import Socket Modules=Socket.Socket()# Create a Socket objectHost =Socket. GetHostName ()# get Local host namePort =12345 # Set Ports.Bind(host, Port)# bound Ports.Listen(5)# Waiting for client connections whileTrue:c, addr =s.Accept()# Establish a client connection. Print ' connection address: ', addr C.Send(' Welcome to the Novice Tutorial! ') c.Close()# Close Connection
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:
#!/usr/bin/python#-*-Coding:utf-8-*-# file name: client.pyImportSocket # import Socket Modules=Socket.Socket()# Create a Socket objectHost =Socket. GetHostName ()# get Local host namePort =12345 # set Port goods.Connect(host, Port)Print s.recv(1024x768)s.Close()
Now we open a terminal, the first terminal executes the server.py file:
$ python server.py
The second terminal executes the client.py file:
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 |
Personal examples
tcpserver.py
#!/usr/bin/python#-*-Coding:utf-8-*-ImportSocketFrom TimeImport ctimehost=Socket. GetHostName () port=12345Bufsize=1024x768Addr= (Host,port) tcpsersock=Socket.Socket() Tcpsersock.Bind(ADDR) Tcpsersock.Listen(5) whileTrue:Print("waitting for connection ...") Tcpclisock,addr=tcpsersock.Accept()Print(' ... connected from: ', addr) whileTrue:data=tcpclisock.recv(BUFSIZE). Decode ()if notData Break Else:Print(' recece data:from hostname=%s hostip&port=%s '% (HOST,ADDR), data) Tcpclisock.Send((' [%s]%s '% (CTime (), data)). Encode ()) Tcpclisock.Close() Tcpsersock.Close()
tcpclient.py
#!/usr/bin/python#-*-Coding:utf-8-*- Import socket fromTime Import ctimeHOST=socket.gethostname ()PORT=12345BUFSIZE=1024x768ADDR=(HOST,PORT)Tcpclisock=socket.socket ()Tcpclisock. Connect (ADDR) while True: Data = input(' please input > ') ifNot data:Break Tcpclisock.send ( data. Encode()) Data = Tcpclisock.recv(BUFSIZE). Decode() ifNot data:Break Print ( data)Tcpclisock. Close ()
udpserver.py
#!/usr/bin/python#-*-Coding:utf-8-*-#udpServer. PYImportSocketFrom TimeImport CTime HOST =Socket. GetHostName () PORT =54321BUFSIZE =1024x768ADDR = (HOST, PORT) Udpsersock =Socket.Socket(Socket. Af_inet,Socket. SOCK_DGRAM) Udpsersock.Bind(ADDR) whileTrue:Print(' Waiting for message ... ') data,addr = Udpsersock.recvfrom (BUFSIZE)Print(data) Udpsersock.sendto (' [%s]%s ' %(CTime (), Data.decode ())). Encode (), addr)Print("Receive from %s:%s"% addr) Udpsersock.Close()
udpclient.py
#!/usr/bin/python#-*-Coding:utf-8-*-#udpServer. PYImportSocketFrom TimeImport CTime HOST =Socket. GetHostName () PORT =54321BUFSIZE =1024x768ADDR = (HOST, PORT) Udpsersock =Socket.Socket(Socket. Af_inet,Socket. SOCK_DGRAM) Udpsersock.Bind(ADDR) whileTrue:Print(' Waiting for message ... ') data,addr = Udpsersock.recvfrom (BUFSIZE)Print(data) Udpsersock.sendto (' [%s]%s ' %(CTime (), Data.decode ())). Encode (), addr)Print("Receive from %s:%s"% addr) Udpsersock.Close()
Daydayup_python Self-study tutorial [13]_ Network programming