Python Network Programming
Python provides two levels of access to web services. :
- Low-level web services support basic Sockets, which provide a standard BSD Sockets API that provides access to all methods of the underlying operating system Socket interface.
- The high-level network service module SocketServer, which provides a server-centric class that simplifies the development of web servers.
What is Socket?
Sockets, also known as "sockets", typically send requests to the network or "receive network requests" through "sockets" to allow communication between processes between hosts or on a single computer.
In Python, we use the socket() function to create a socket with the following syntax:
socket.socket Span>([family[, type[,proto]]])< /pre>
- family: The socket family can make AF_UNIX or AF_INET
- type: The socket type can be divided intodepending on whether it is connection-oriented or non-connected.
- protocol: Generally, the default is 0.
Socket object (built-in) method
function Description Server Side Sockets s.bind() Bind the address (host, port) to the socket. Under AF_INET, the address is represented in the form of a tuple (host, port). s.listen() Start TCP listening. The backlog specifies the maximum number of connections 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 accept TCP client connections, (blocking) waiting for the connection to arrive Client Sockets s.connect() Actively initializes the TCP server connection. The format of the general address is a tuple (hostname, port). If the connection is wrong, a socket.error error is returned. s.connect_ex() The extended version of the connect() function returns an error code when an error occurs instead of throwing an exception Public function socket function s.recv() Receive TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. The flag provides additional information about the message and can usually be ignored. s.send() Send TCP data and send the data in string to the connected socket. The return value is the number of bytes to send, which may be less than the byte size of string. s.sendall() Completely send TCP data and send TCP data completely. Sends the data in the string to the connected socket, but tries to send all the data before returning. Returns None successfully, and throws an exception if it fails. s.recvfrom() Receive UDP data, similar to recv(), but the return value is (data, address). Where data is the string containing the received data, and address is the socket address of the transmitted data. s.sendto() Send UDP data, send the data to the socket, address is a tuple of the form (ipaddr, port), specify the remote address. The return value is the number of bytes sent. s.close() Close the socket s.getpeername() Returns the remote address of the connection socket. The return value is usually a tuple (ipaddr, port). s.getsockname() returns the socket's own address. Usually 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 socket operations. Timeout is a floating point number in seconds. A value of None indicates no timeout. In general, the timeout should be set when the socket is just created, as they might be used for connected operations (such as connect()) s.gettimeout() Returns the value of the current timeout period in seconds. If no timeout period is set, it returns None. s.fileno() Returns the file descriptor of the socket. s.setblocking(flag) If the flag is 0, the socket is set to non-blocking mode, otherwise the socket is set to blocking mode (default). In non-blocking mode, if call to recv() does not find any data, or if the send() call cannot send data immediately, it will cause a socket.error exception. s.makefile() Create a file associated with the socket
We use the socket module's socket function to create a socket object. The socket object can set a socket service by calling other functions.
Now we can specify the port(port) of the service by calling the bind(hostname, port) function.
Next, we call the socket object's accept method. This method waits for a connection from the client and returns an connection object indicating that it is connected to the client.
The complete code is as follows:#!/usr/bin/python # -*- coding: UTF-8 -*- # Filename: server.py import socket # import socket module s = socket.socket() # create a socket object< Span class="pln"> Host= socket.gethostname() # Get local hostname Port = 12345 # Set Port s.bind((host, port)) # binding port s.listen(5) # Waiting for client connection while True: c, addr = s.accept() # Establish a client connection。 print 'Connection address：', addr c.send('Welcome to the rookie tutorial！') c.close() # Close the connection
Next we write a simple client instance to connect to the service created above. The port number is 12345.The
socket.connect(hosname, port ) method opens a TCP connection to a service provider whose host is hostname is port. Once connected, we can get the data from the server, remembering that the connection needs to be closed after the operation is completed.
The complete code is as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- # Filename: client.py import socket # 导入 socket Module s = socket.socket() # create socket Object host = socket.gethostname() # Object...... port = 12345 # Set the port number s.connect((host, port)) print s.recv(1024) s.close()
Now we open two terminals, the first terminal executes the server.py file:
$ python server.py
The second terminal executes the client.py file:
$ python client.py Welcome to the rookie tutorial!
At this point, we will open the first terminal and you will see the following information output:
Connected Address: (< /span>'192.168.0.118', 62461)
Python Internet Module
Here are some important modules for Python network programming:
|Agreement||Features||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|
|Gopher||Information lookup||70||gopherlib, urllib|