第五章 并发编程与网络通信
5.1 并发编程
5.1.1 多线程编程
基础线程操作
import threading
import time
def download_file ( url) :
print ( f"开始下载 { url} " )
time. sleep( 2 )
print ( f"完成下载 { url} " )
threads = [ ]
for i in range ( 3 ) :
t = threading. Thread( target= download_file, args= ( f"pic_ { i} .jpg" , ) )
threads. append( t)
t. start( )
for t in threads:
t. join( )
线程同步与锁机制
class BankAccount :
def __init__ ( self) :
self. balance = 1000
self. lock = threading. Lock( )
def transfer ( self, amount) :
with self. lock:
current = self. balance
current += amount
time. sleep( 0.1 )
self. balance = current
account = BankAccount( )
threads = [ ]
for _ in range ( 100 ) :
t = threading. Thread( target= account. transfer, args= ( 100 , ) )
threads. append( t)
t. start( )
for t in threads:
t. join( )
print ( "最终余额:" , account. balance)
5.1.2 多进程编程
进程基础
from multiprocessing import Process
import os
def task ( name) :
print ( f"子进程 { name} PID: { os. getpid( ) } " )
if __name__ == "__main__" :
processes = [ ]
for i in range ( 3 ) :
p = Process( target= task, args= ( i, ) )
processes. append( p)
p. start( )
for p in processes:
p. join( )
进程间通信
from multiprocessing import Queue, Process
def producer ( q) :
for i in range ( 5 ) :
q. put( i)
print ( f"生产数据 { i} " )
def consumer ( q) :
while True :
item = q. get( )
if item is None :
break
print ( f"消费数据 { item} " )
if __name__ == "__main__" :
q = Queue( )
p1 = Process( target= producer, args= ( q, ) )
p2 = Process( target= consumer, args= ( q, ) )
p1. start( )
p2. start( )
p1. join( )
q. put( None )
p2. join( )
5.1.3 异步编程(协程)
async/await基础
import asyncio
async def fetch_data ( url) :
print ( f"开始请求 { url} " )
await asyncio. sleep( 2 )
print ( f"完成请求 { url} " )
return f" { url} 的响应数据"
async def main ( ) :
tasks = [
fetch_data( "https://api/data1" ) ,
fetch_data( "https://api/data2" )
]
results = await asyncio. gather( * tasks)
print ( "所有请求完成:" , results)
asyncio. run( main( ) )
异步HTTP客户端
import aiohttp
import asyncio
async def fetch_page ( url) :
async with aiohttp. ClientSession( ) as session:
async with session. get( url) as response:
return await response. text( )
async def main ( ) :
urls = [
"http://example.com" ,
"http://python.org"
]
tasks = [ fetch_page( url) for url in urls]
pages = await asyncio. gather( * tasks)
print ( f"获取到 { len ( pages) } 个页面" )
asyncio. run( main( ) )
5.2 网络通信
5.2.1 Socket编程
TCP通信示例
import socket
server = socket. socket( socket. AF_INET, socket. SOCK_STREAM)
server. bind( ( 'localhost' , 8888 ) )
server. listen( )
print ( "等待连接..." )
client, addr = server. accept( )
print ( f"连接来自 { addr} " )
client. send( b"Welcome to TCP server" )
data = client. recv( 1024 )
print ( "收到消息:" , data. decode( ) )
client. close( )
client = socket. socket( socket. AF_INET, socket. SOCK_STREAM)
client. connect( ( 'localhost' , 8888 ) )
print ( "收到服务端消息:" , client. recv( 1024 ) . decode( ) )
client. send( b"Hello from client" )
client. close( )
UDP通信示例
server = socket. socket( socket. AF_INET, socket. SOCK_DGRAM)
server. bind( ( 'localhost' , 9999 ) )
while True :
data, addr = server. recvfrom( 1024 )
print ( f"收到来自 { addr} 的消息: { data. decode( ) } " )
server. sendto( b"UDP response" , addr)
client = socket. socket( socket. AF_INET, socket. SOCK_DGRAM)
client. sendto( b"Hello UDP" , ( 'localhost' , 9999 ) )
print ( "收到回复:" , client. recv( 1024 ) . decode( ) )
5.2.2 HTTP通信
Requests库应用
import requests
response = requests. get( "https://api.github.com" )
print ( "状态码:" , response. status_code)
print ( "响应头:" , response. headers[ 'Content-Type' ] )
data = { "user" : "admin" , "password" : "secret" }
response = requests. post( "https://httpbin.org/post" , json= data)
print ( "响应JSON:" , response. json( ) )
简易HTTP服务器
from http. server import HTTPServer, BaseHTTPRequestHandler
class MyHandler ( BaseHTTPRequestHandler) :
def do_GET ( self) :
self. send_response( 200 )
self. send_header( 'Content-type' , 'text/html' )
self. end_headers( )
self. wfile. write( b"<h1>Hello from Python Server</h1>" )
server = HTTPServer( ( 'localhost' , 8000 ) , MyHandler)
print ( "服务器启动于 http://localhost:8000" )
server. serve_forever( )
5.2.3 WebSocket通信
import asyncio
import websockets
async def echo_server ( websocket) :
async for message in websocket:
print ( f"收到消息: { message} " )
await websocket. send( f"服务器回复: { message} " )
async def main ( ) :
async with websockets. serve( echo_server, "localhost" , 8765 ) :
await asyncio. Future( )
asyncio. run( main( ) )
5.3 综合应用案例
异步网络爬虫
import aiohttp
import asyncio
from bs4 import BeautifulSoup
async def fetch_and_parse ( url) :
async with aiohttp. ClientSession( ) as session:
async with session. get( url) as response:
html = await response. text( )
soup = BeautifulSoup( html, 'html.parser' )
return soup. title. string
async def main ( ) :
urls = [
"http://example.com" ,
"https://python.org" ,
"https://aiohttp.readthedocs.io"
]
tasks = [ fetch_and_parse( url) for url in urls]
results = await asyncio. gather( * tasks)
for url, title in zip ( urls, results) :
print ( f" { url} 的标题: { title} " )
asyncio. run( main( ) )
多用户聊天室
import socket
import threading
clients = [ ]
def handle_client ( client) :
while True :
try :
msg = client. recv( 1024 ) . decode( )
if not msg:
break
print ( f"收到消息: { msg} " )
broadcast( msg, client)
except :
break
def broadcast ( msg, sender) :
for client in clients:
if client != sender:
try :
client. send( msg. encode( ) )
except :
clients. remove( client)
def start_server ( ) :
server = socket. socket( socket. AF_INET, socket. SOCK_STREAM)
server. bind( ( 'localhost' , 9000 ) )
server. listen( 5 )
while True :
client, addr = server. accept( )
print ( f"新连接: { addr} " )
clients. append( client)
thread = threading. Thread( target= handle_client, args= ( client, ) )
thread. start( )
if __name__ == "__main__" :
start_server( )