Techniques of using Python scripts for network programming under Linux platform
In today's Internet era, network programming has become an important technology, whether it is website development, Whether it is data transmission or server construction, network programming support is indispensable. As a simple and powerful programming language, Python also provides a wealth of libraries and modules, making network programming easier and more efficient. This article will introduce some techniques for using Python scripts for network programming under the Linux platform, and give specific code examples.
Whether you are building a server or a client, you must first establish a basic network connection. Python's socket module provides a series of interfaces to easily establish connections. The following is a simple client code example:
import socket # 创建一个 TCP/IP 的 socket 对象 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义服务器的 IP 地址和端口号 server_address = ('127.0.0.1', 8080) # 连接服务器 client_socket.connect(server_address) # 发送数据 message = 'Hello, server!' client_socket.sendall(message.encode()) # 接收服务器的响应 response = client_socket.recv(1024) print('Received:', response.decode()) # 关闭连接 client_socket.close()
In the code, first create a socket object through the socket.socket()
function, and then use connect()
Function to connect to the server. Next, you can use the sendall()
function to send data and the recv()
function to receive the server's response. Finally, the connection is closed through the close()
function.
In order to improve the concurrency performance of network programming, you can use multi-threading or multi-process to handle multiple connections. Python's threading
and multiprocessing
modules provide rich interfaces that can easily implement multi-threading and multi-process programming. The following is a code example of a simple multi-threaded server:
import socket import threading # 处理客户端请求的线程函数 def handle_client(client_socket): # 接收客户端的数据 request = client_socket.recv(1024) print('Received:', request.decode()) # 发送响应给客户端 response = 'Hello, client!' client_socket.sendall(response.encode()) # 关闭连接 client_socket.close() # 创建一个 TCP/IP 的 socket 对象 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义服务器的 IP 地址和端口号 server_address = ('127.0.0.1', 8080) # 绑定地址和端口号 server_socket.bind(server_address) # 开始监听连接 server_socket.listen(5) print('Server is running...') while True: # 等待新的客户端连接 client_socket, client_address = server_socket.accept() print('Connected by:', client_address) # 创建新的线程来处理客户端请求 client_thread = threading.Thread(target=handle_client, args=(client_socket,)) client_thread.start()
In the code, a socket object is created through the socket.socket()
function, and bind()
Function binds the server's address and port together. Then start listening for connections through the listen()
function. In the main loop, use the accept()
function to wait for new client connections and create a new thread for each client to handle client requests.
In order to improve the efficiency of network programming, you can use non-blocking I/O for data transmission. Python's select
and selectors
modules provide some interfaces that can implement non-blocking I/O operations. The following is a simple code example using the selectors
module:
import socket import selectors # 创建一个 TCP/IP 的 socket 对象 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 定义服务器的 IP 地址和端口号 server_address = ('127.0.0.1', 8080) # 设置 socket 为非阻塞模式 server_socket.setblocking(False) # 绑定地址和端口号 server_socket.bind(server_address) # 开始监听连接 server_socket.listen(5) print('Server is running...') # 创建一个 selectors 对象 sel = selectors.DefaultSelector() # 注册 socket 对象到 selectors 对象中 sel.register(server_socket, selectors.EVENT_READ) while True: # 获取发生事件的 socket 对象 events = sel.select(timeout=None) for key, mask in events: if key.fileobj == server_socket: # 有新的客户端连接 client_socket, client_address = server_socket.accept() print('Connected by:', client_address) # 设置客户端 socket 为非阻塞模式 client_socket.setblocking(False) # 注册客户端 socket 到 selectors 对象中 sel.register(client_socket, selectors.EVENT_READ) else: # 有客户端发送请求 client_socket = key.fileobj # 接收客户端的数据 request = client_socket.recv(1024) print('Received:', request.decode()) # 发送响应给客户端 response = 'Hello, client!' client_socket.sendall(response.encode()) # 注销客户端 socket sel.unregister(client_socket) # 关闭连接 client_socket.close()
In the code, first set the socket object to non-blocking mode. Then create a selectors object through the selectors.DefaultSelector()
function, and use the sel.register()
function to register the socket object into the selectors object. In the main loop, use the sel.select()
function to wait for the socket object where the event occurs, and then perform corresponding operations based on the specific event type.
Summary
This article introduces some techniques for using Python scripts for network programming under the Linux platform, and gives specific code examples. As long as you master these basic technologies, you can easily perform network programming and realize data transmission between the server and the client. At the same time, you can further learn and explore other advanced network programming technologies, such as using frameworks to simplify development and implement more complex functions. I wish you all more success on the road to network programming!
The above is the detailed content of Tips on using Python scripts for network programming under Linux platform. For more information, please follow other related articles on the PHP Chinese website!