foreword
Yesterday I explained the first time about getting started with python from scratch, and the compulsory content of programming grammar, such as getting started with python3, lists and tuples, strings, dictionaries, conditions, loops and other statements, functions, object-oriented, exceptions and file processing
1 .Learn python from scratch with me (1) Compulsory programming grammar
Today I will talk about the second part: python concurrent programming: network programming
This series of articles is based on the following learning route. Due to the large content: learning python from scratch to advanced advanced roadmap
Pay attention to the official account: python technology training camp , learn advanced step by step
Python resources suitable for zero-based learning and advanced people:
① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders
Chapter 1: Network Programming
1. Network programming
Network programming refers to programming techniques that use computer networks for communication. In Python, socket
network programming can be implemented using modules.
socket
It is a network programming library that encapsulates TCP/IP
the protocol, which provides a general network programming interface that can be used to create client and server programs. In Python, you use socket
modules to create socket
objects and then use that object for network communication.
The following is a simple network programming example, in which a server and a client are created, the client sends a message to the server, and the server prints out the message after receiving it:
Server side code:
import socket
# 创建socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
# 监听端口
server_socket.listen(5)
print('服务器已启动,等待客户端连接...')
# 等待客户端连接
client_socket, client_address = server_socket.accept()
print('客户端已连接,地址为:', client_address)
# 接收客户端消息
data = client_socket.recv(1024)
print('接收到客户端消息:', data.decode())
# 关闭socket连接
client_socket.close()
server_socket.close()
Client code:
import socket
# 创建socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('127.0.0.1', 8888))
# 发送消息
client_socket.send('Hello, server!'.encode())
# 关闭socket连接
client_socket.close()
PyCharm
To compile and run Matlab
files in , you need to install Matlab
and configure environment variables first. Then, PyCharm
open Matlab
the file in , click the run button to compile and run Matlab
the file. If parameters need to be passed, they can be set in the run configuration.
2. Introduction to TCP/IP
TCP/IP
It is a network protocol, which is the basic protocol of the Internet. TCP/IP
The protocol family includes many protocols, the most important of which is TCP
the and IP
protocol.
TCP
The protocol is a connection-oriented protocol that provides reliable data transmission services. TCP
The protocol establishes a connection through a three-way handshake, and then ensures reliable data transmission through data segmentation and confirmation mechanisms.
IP
The protocol is a connectionless protocol that provides data packet transmission services. The IP protocol determines the transmission path of the data packet through the routing algorithm, and then transmits the data packet to the destination.
In network programming, we usually use TCP
protocols for data transmission. TCP
The protocol provides reliable data transmission services, and is suitable for scenarios that need to ensure the reliability of data transmission, such as file transmission and mail transmission. The protocol IP
is suitable for scenarios that require fast data transmission, such as video streaming, real-time communication, etc.
3. Network Design Module
1. Introduction to Socket
Socket
Is a communication mechanism that allows different processes to communicate over a network. In Python, Socket
this is socket
achieved through modules. Socket
Typically used for communication between clients and servers, but can also be used for communication between processes.
2. Socket module use
Modules in Python socket
provide a set of functions and classes for creation and manipulation Socket
. Commonly used functions and classes include:
socket()
: Create a Socket object.bind()
: Bind the Socket to a specific address and port.listen()
: Start listening for connection requests.accept()
: Accept a connection request and return a new Socket object.connect()
: Connect to a remote Socket.send()
:send data.recv()
:Receive data.
3. Server
In Python, you can use socket
modules to create a server. A server usually needs to bind to a specific address and port and listen for connection requests. When a client connects to the server, the server accepts the connection request and creates a new Socket
object to handle the client request.
Here is a simple Python server example:
import socket
HOST = '127.0.0.1' # 服务器地址
PORT = 8888 # 服务器端口号
# 创建一个Socket对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定到地址和端口
server_socket.bind((HOST, PORT))
# 开始监听连接请求
server_socket.listen(1)
print('Server is running on {}:{}'.format(HOST, PORT))
while True:
# 接受一个连接请求,并返回一个新的Socket对象
client_socket, client_address = server_socket.accept()
print('Client connected from {}:{}'.format(client_address[0], client_address[1]))
# 处理客户端请求
data = client_socket.recv(1024)
print('Received data: {}'.format(data.decode()))
# 发送响应数据
response = 'Hello, client!'
client_socket.send(response.encode())
# 关闭连接
client_socket.close()
4. Client
In Python, socket
a client can be created using a module. Clients usually need to connect to a remote Socket
and send request data. When the server responds to the request, the client receives the response data.
Here is a simple Python client example:
import socket
HOST = '127.0.0.1' # 服务器地址
PORT = 8888 # 服务器端口号
# 创建一个Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到远程Socket
client_socket.connect((HOST, PORT))
# 发送请求数据
request = 'Hello, server!'
client_socket.send(request.encode())
# 接收响应数据
response = client_socket.recv(1024)
print('Received data: {}'.format(response.decode()))
# 关闭连接
client_socket.close()
5. File Downloader
A file downloader is a common web application that downloads files from a remote server and saves them locally. In Python, file downloaders can be implemented using socket
modules and modules.urllib
Here is a simple Python file downloader example:
import socket
import urllib.request
HOST = '127.0.0.1' # 服务器地址
PORT = 8888 # 服务器端口号
FILE_URL = 'http://example.com/file.txt' # 文件下载地址
FILE_NAME = 'file.txt' # 文件保存路径
# 创建一个Socket对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接到远程Socket
client_socket.connect((HOST, PORT))
# 发送请求数据
request = 'GET {}\r\n'.format(FILE_URL)
client_socket.send(request.encode())
# 接收响应数据
response = client_socket.recv(1024)
print('Received data: {}'.format(response.decode()))
# 下载文件并保存到本地
with open(FILE_NAME, 'wb') as f:
while True:
data = client_socket.recv(1024)
if not data:
break
f.write(data)
# 关闭连接
client_socket.close()
4. Supplementary content
1. UDP protocol in network programming
UDP (User Datagram Protocol) is a connectionless and unreliable transmission protocol. It does not guarantee the reliability and sequence of data packets, but the transmission speed is fast, and it is suitable for some application scenarios that do not require high data reliability. Such as video, audio and other real-time transmission.
In Python, network programming of protocols socket
can be implemented using modules UDP
. Here is an example of a simple UDP
server and client:
UDP
server:
import socket
# 创建UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
while True:
# 接收数据
data, addr = server_socket.recvfrom(1024)
print('Received from %s:%s.' % addr)
print('Data: %s' % data.decode())
# 发送数据
server_socket.sendto('Hello, client!'.encode(), addr)
UDP
client:
import socket
# 创建UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
client_socket.sendto('Hello, server!'.encode(), ('127.0.0.1', 8888))
# 接收数据
data, addr = client_socket.recvfrom(1024)
print('Received from %s:%s.' % addr)
print('Data: %s' % data.decode())
# 关闭套接字
client_socket.close()
In UDP
the protocol, the destination address and port number need to be specified when sending data, and the address and port number of the sender will be returned when receiving data. Since UDP
the protocol does not guarantee the reliability and sequence of data, problems such as data loss, duplication, and disorder need to be considered in practical applications.
2. The difference between UDP protocol and TCP protocol
UDP
Protocol and TCP
protocol are two commonly used network transmission protocols, and they have the following differences:
-
Connection mode :
TCP
The protocol is a connection-oriented protocol, whileUDP
the protocol is a connectionless protocol.TCP
Protocols require a connection to be established before transferring data, whileUDP
protocols do not. -
Reliability :
TCP
The protocol is a reliable protocol, which guarantees the reliable transmission of data, whileUDP
the protocol is an unreliable protocol, which does not guarantee the reliable transmission of data. -
Transmission efficiency :
UDP
The protocolTCP
is more efficient than the protocol transmission, becauseUDP
the protocol does not need to establish a connection and maintain the connection state, butTCP
the protocol does. -
Packet size :
UDP
The packet size of the protocol transmission is limited to 64KB, whileTCP
the protocol has no limit. -
Application scenarios :
TCP
The protocol is suitable for scenarios that require high reliability of data transmission, such as file transfer, email transmission, etc.; and theUDP
protocol is suitable for scenarios that require high real-time data transmission, such as live video broadcasting, voice calls, etc.
3. UDP protocol code implementation
UDP
The protocol is a connectionless protocol, which does not guarantee the reliability and sequence of data transmission, but has the advantage of fast transmission speed. UDP
The following is the code implementation of network programming using protocols in Python :
Server side code:
import socket
# 创建UDP套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定IP地址和端口号
server_socket.bind(('127.0.0.1', 8888))
# 接收数据
while True:
data, addr = server_socket.recvfrom(1024)
print('Received from %s:%s.' % addr)
print('Data: %s' % data.decode())
# 发送数据
server_socket.sendto('Hello, client!'.encode(), addr)
Client code:
import socket
# 创建UDP套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 发送数据
client_socket.sendto('Hello, server!'.encode(), ('127.0.0.1', 8888))
# 接收数据
data, addr = client_socket.recvfrom(1024)
print('Received from %s:%s.' % addr)
print('Data: %s' % data.decode())
# 关闭套接字
client_socket.close()
In the above code, the server first creates a UDP
socket and binds IP
the address and port number. Then recvfrom()
receive the data sent by the client through the method, and sendto()
send the data to the client through the method. The client also creates a UDP
socket, and sendto()
sends data to the server through the method, and then recvfrom()
receives the data sent by the server through the method. Finally, the client closes the socket.
This series of articles is based on the following learning route. Due to the large content: learning python from scratch to advanced advanced roadmap
Pay attention to the official account: python technology training camp , learn advanced step by step
Python resources suitable for zero-based learning and advanced people:
① Tencent certified python complete project practical tutorial notes PDF
② More than a dozen major manufacturers python interview topic PDF
③ Python full set of video tutorials (zero foundation-advanced advanced JS reverse)
④ Hundreds of project actual combat + source code + notes
⑤ Programming grammar - machine learning -Full-stack development-data analysis-crawler-APP reverse engineering and other full set of projects + documents
⑥ Exchange and study
⑦ Want to take part-time orders
The next chapter is about: python concurrent programming: multithreading