Python network programming


Python provides two levels of access to network services. :

  • The low-level network service supports basic Socket, which provides the standard BSD Sockets API and can access all methods of the underlying operating system Socket interface.

  • High-level network service module SocketServer, which provides server center classes that can simplify the development of network servers.


What is Socket?

Socket is also called "socket". Applications usually make requests to or respond to the network through "sockets" Requests enable communication between hosts or between processes on a computer.


socket() function

In Python, we use the socket() function to create a socket. The syntax format is as follows:

socket.socket([family[, type[, proto]]])

Parameters

  • family: The socket family can be AF_UNIX or AF_INET

  • type: The socket type can be divided into ## according to whether it is connection-oriented or non-connection #SOCK_STREAM or SOCK_DGRAM

  • protocol: Generally left unfilled, the default is 0.

Socket object (built-in) methods

## Client sockets.connect()Actively initializes the TCP server connection. Generally, the format of address is a tuple (hostname, port). If a connection error occurs, a socket.error error is returned. s.connect_ex()Extended version of the connect() function, returns an error code when an error occurs instead of throwing an exceptionPublic purpose socket functions.recv()Receives TCP data. The data is returned in the form of a string. bufsize specifies the data to be received. Maximum amount of data. 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 string's byte size. s.sendall()Send TCP data completely, send TCP data completely. Sends the data in a string to the connected socket, but attempts to send all data before returning. Returns None on success, throws an exception on failure. s.recvform()Receives UDP data, similar to recv(), but the return value is (data, address). Where data is a string containing the received data, and address is the socket address to which the data is sent. s.sendto()Send UDP data, send the data to the socket, address is a tuple in the form of (ipaddr, port), specifying the remote address. The return value is the number of bytes sent. s.close()Close the sockets.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)Set the value of the given socket option. s.getsockopt(level,optname[.buflen])Returns the value of the socket option. s.settimeout(timeout)Set the timeout period for socket operations. timeout is a floating point number in seconds. A value of None means there is no timeout period. Generally, timeouts should be set when the socket is first created, as they may be used for connection operations (such as connect()) s.gettimeout()Return the value of the current timeout period in seconds. If no timeout period is set, None is returned. s.fileno()Returns the socket’s file descriptor.
FunctionDescription
Server-side socket
s.bind()Bind address (host, port) to the socket, in AF_INET Below, the address is expressed 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 should be at least 1, and 5 will be fine for most applications.
s.accept() Passively accept TCP client connections, (blocking) waiting for the arrival of the connection
s.setblocking(flag)If flag is 0, set the socket to non-blocking mode, otherwise set the socket to blocking mode ( default value). In non-blocking mode, if no data is found by calling recv(), or the send() call cannot send data immediately, a socket.error exception will be caused.
s.makefile()Create a file associated with the socket

Simple example

Server

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.

Now we can specify the port(port) of the service by calling the bind(hostname, port) function.

Next, we call the accept method of the socket object. This method waits for the client's connection and returns the connection object, indicating that it is connected to the client.

The complete code is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:server.py

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口
s.bind((host, port))        # 绑定端口

s.listen(5)                 # 等待客户端连接
while True:
    c, addr = s.accept()     # 建立客户端连接。
    print '连接地址:', addr
    c.send('欢迎访问php中文网!')
    c.close()                # 关闭连接

Client

Next we write a simple client instance to connect to the service created above. The port number is 12345.

socket.connect(hosname, port) method opens a TCP connection to the service provider with host hostname and port port. After connecting, we can post data from the server. Remember, the connection needs to be closed after the operation is completed.

The complete code is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件名:client.py

import socket               # 导入 socket 模块

s = socket.socket()         # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12345                # 设置端口好

s.connect((host, port))
print s.recv(1024)
s.close()

Now we open two terminals, and the first terminal executes the server.py file:

$ python server.py

The second terminal executes the client.py file :

$ python client.py 
欢迎访问php中文网!

This is the first terminal we open again, and we will see the following information output:

连接地址: ('192.168.0.118', 62461)

Python Internet module

The following are listed Some important modules of Python network programming:

ProtocolFunction usagePort numberPython module
HTTPWeb page access80httplib, urllib, xmlrpclib
NNTP Read and post news articles, commonly known as "posts"119nntplib
FTP File transfer20ftplib, urllib
SMTPSend mail25smtplib
POP3Receive mail110poplib
IMAP4Get Mail143imaplib
TelnetCommand Line 23telnetlib
GopherInformation lookup70gopherlib, urllib

For more information, please refer to the Python Socket Library and Modules on the official website.