Python3 network programming

Python provides two levels of access to the network service.

  • Low-level network services support the basic Socket, which provides a standard BSD Sockets API that provides full access to the underlying operating system Socket interface.
  • A high-level network service module, SocketServer, provides a server hub class that simplifies the development of network servers.

What is Socket?

Socket is also known as a socket, and applications typically use sockets to make or respond to network requests to the network, allowing communication between hosts or processes on a computer.

socket() function

In Python, we use the socket() function to create sockets in the following syntax format:

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


  • Family: The socket family can make AF_UNIX or AF_INET
  • Type: The socket type can be divided into a connection-oriented or SOCK_STREAM or SOCK_DGRAM
  • Protocol: Generally do not fill in the default is 0.

The Socket object (built-in) method

Function Describe
The server-side socket
s.bind() The binding address (host, port) to the socket, which is AF_INET in the form of a metagroup (host, port).
s.listen() Start TCP listening. B acklog specifies the maximum number of connections that the operating system can suspend before denying a connection. The value is at least 1, and most applications set it to 5.
s.accept() Passively accept the TCP client connection, (blocking) waiting for the connection to arrive
The client socket
s.connect() Active initialization of TCP server connections. The general address is formatted as a metagroup (hostname, port), and if the connection goes wrong, an socket.error error is returned.
s.connect_ex() An extended version of the connect() function that returns an error code when an error occurs, rather than throwing an exception
A common-purpose socket function
s.recv() Receive tCP data, the data is returned as a string, and the bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can often be ignored.
s.send() Sends TCP data, sends data from the string to the connected socket. Returns the number of bytes to send, which may be less than the byte size of the string.
s.sendall() Send TCP data in its entirety and TCP data in its entirety. S ends the data from the string to the connected socket, but attempts to send all the data before returning. None is returned successfully, and an exception is thrown if it fails.
s.recvfrom() Receive UDP data, similar to recv(), but with a return value of (data, address). Where data is the string that contains the received data, address is the socket address that sends the data.
s.sendto() Send UDP data, send data to sockets, address is a group in the form of (ipaddr, port), specifying a 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 metagroup (ipaddr, port).
s.getsockname() Returns the socket's own address. Usually a metagroup (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) Set the super-period of socket operation, timeout is a floating point in seconds. A value of None indicates that there is no super-period. In general, periods should be set when sockets are first created, as they may be used for connected operations such as connect()
s.gettimeout() Returns the value of the current super-period in seconds, or None if the super-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 non-blocking mode, otherwise the socket is set to blocking mode (the default). In non-blocking mode, an socket.error exception is caused if the call recv() does not find any data, or if the send() call does not send the data immediately.
s.makefile() Create a file that is related to the socket

A simple example

The service side

We use the socket function of the socket module to create an socket object. The socket object can set up an socket service by calling other functions.

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

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

The full code is as follows:

# 文件名

# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
serversocket = socket.socket(
            socket.AF_INET, socket.SOCK_STREAM) 

# 获取本地主机名
host = socket.gethostname()

port = 9999

# 绑定端口
serversocket.bind((host, port))

# 设置最大连接数,超过后排队

while True:
    # 建立客户端连接
    clientsocket,addr = serversocket.accept()      

    print("连接地址: %s" % str(addr))
    msg='欢迎访问W3Cschool教程!'+ "\r\n"


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

The socket.connect (hosname, port) method opens a TCP connection to the host for the hostname port for the port provider. Once connected, we can take late data from the service side and remember that we need to close the connection when the operation is complete.

The full code is as follows:

# 文件名

# 导入 socket、sys 模块
import socket
import sys

# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# 获取本地主机名
host = socket.gethostname() 

# 设置端口好
port = 9999

# 连接服务,指定主机和端口
s.connect((host, port))

# 接收小于 1024 字节的数据
msg = s.recv(1024)


print (msg.decode('utf-8'))

Now let's open a terminal, the first terminal executes file:

$ python3

The second terminal executes file:

$ python3 

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

连接地址: ('', 33397)

Python Internet module

Here are some important modules for Python network programming:

Agreement Functional useful The port number Python module
HTTP Web page 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 a message 25 smtplib
POP3 Receive the message 110 poplib
IMAP4 Get the message 143 imaplib
Telnet The command line 23 telnetlib
Gopher Information lookup 70 gopherlib, urllib

For more information, see Python Socket Library and Modules on the website.