Python网络编程的 11 个重要知识点

开发
网络编程就是让程序通过网络发送数据给其他程序或接收其他程序的数据。Python中的网络编程主要使用 socket 模块。

1. 网络编程基础

网络编程就是让程序通过网络发送数据给其他程序或接收其他程序的数据。Python中的网络编程主要使用 socket 模块。

2. TCP服务器示例

import socket

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

# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 监听连接
server_socket.listen(5)
print('Server listening on port:', port)

while True:
    # 建立客户端连接
    client_socket, addr = server_socket.accept()
    print('Got connection from', addr)
    
    # 接收客户端消息
    msg = client_socket.recv(1024).decode()
    print('Message from client:', msg)
    
    # 发送响应
    response = 'Thank you for connecting'
    client_socket.send(response.encode())
    
    # 关闭连接
    client_socket.close()

这个简单的服务器监听12345端口,当有客户端连接时,会打印客户端地址,并接收客户端的消息,然后发送响应并关闭连接。

3. TCP客户端示例

import socket

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

# 连接服务器
host = 'localhost'
port = 12345
client_socket.connect((host, port))

# 发送消息
msg = 'Hello, server!'
client_socket.send(msg.encode())

# 接收响应
response = client_socket.recv(1024).decode()
print('Response from server:', response)

# 关闭连接
client_socket.close()

这个简单的客户端连接服务器,发送一条消息,接收服务器的响应,并关闭连接。

4. UDP服务器示例

import socket

# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

print('Server listening on port:', port)

while True:
    # 接收客户端消息
    msg, addr = server_socket.recvfrom(1024)
    print('Message from client:', msg.decode(), 'at', addr)
    
    # 发送响应
    response = 'Thank you for your message'
    server_socket.sendto(response.encode(), addr)

这个简单的UDP服务器监听12345端口,接收客户端的消息,然后发送响应。

5. UDP客户端示例

import socket

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 发送消息
host = 'localhost'
port = 12345
msg = 'Hello, server!'
client_socket.sendto(msg.encode(), (host, port))

# 接收响应
response, addr = client_socket.recvfrom(1024)
print('Response from server:', response.decode())

# 关闭连接
client_socket.close()

这个简单的UDP客户端发送一条消息,接收服务器的响应,并关闭连接。

6. 多线程TCP服务器示例

import socket
import threading

def handle_client(client_socket, addr):
    print('Got connection from', addr)
    
    msg = client_socket.recv(1024).decode()
    print('Message from client:', msg)
    
    response = 'Thank you for connecting'
    client_socket.send(response.encode())
    
    client_socket.close()

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

# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 监听连接
server_socket.listen(5)
print('Server listening on port:', port)

while True:
    # 建立客户端连接
    client_socket, addr = server_socket.accept()
    # 在新线程中处理客户端连接
    thread = threading.Thread(target=handle_client, args=(client_socket, addr))
    thread.start()

这个服务器使用多线程处理多个客户端连接,每个客户端连接都在一个新线程中处理。

7. 非阻塞I/O TCP服务器示例

import socket
import select

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

# 设置为非阻塞模式
server_socket.setblocking(False)

# 绑定端口
host = 'localhost'
port = 12345
server_socket.bind((host, port))

# 监听连接
server_socket.listen(5)
print('Server listening on port:', port)

inputs = [server_socket]
outputs = []

while True:
    readable, writable, exceptional = select.select(inputs, outputs, inputs)
    
    for sock in readable:
        if sock == server_socket:
            # 建立客户端连接
            client_socket, addr = server_socket.accept()
            client_socket.setblocking(False)
            inputs.append(client_socket)
            print('Got connection from', addr)
        else:
            # 接收客户端消息
            data = sock.recv(1024)
            if data:
                print('Message from client:', data.decode())
                sock.send(data.upper())
            else:
                # 客户端断开连接
                print('Client disconnected')
                inputs.remove(sock)
                sock.close()

这个非阻塞TCP服务器使用select模块同时处理多个客户端连接,提高了程序的响应速度。

8. 使用HTTP协议示例

from http.server import HTTPServer, BaseHTTPRequestHandler

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message = 'Hello, World!'
        self.wfile.write(message.encode())

# 创建 HTTP 服务器
server_address = ('localhost', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

print('Starting simple HTTP server...')
httpd.serve_forever()

这个简单的HTTP服务器监听8000端口,当收到GET请求时,返回“Hello, World!”的响应。

9. 发送HTTP请求示例

首先安装requests库:

pip install requests

然后编写代码:

import requests

url = 'http://localhost:8000'
response = requests.get(url)

print('Response status code:', response.status_code)
print('Response content:', response.text)

这段代码向本地HTTP服务器发送GET请求,并打印响应的状态码和内容。

10. WebSocket编程示例

首先安装websockets库:

pip install websockets

然后编写代码:

import asyncio
import websockets

async def echo(websocket, path):
    async for message in websocket:
        print(f'Received message: {message}')
        await websocket.send(message)

# 创建 WebSocket 服务器
start_server = websockets.serve(echo, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

这个简单的WebSocket服务器监听8765端口,当收到消息时,将其原样返回。

11. 使用WebSocket客户端示例

import asyncio
import websockets

async def send_message():
    uri = 'ws://localhost:8765'
    async with websockets.connect(uri) as websocket:
        message = 'Hello, WebSocket!'
        await websocket.send(message)
        print(f'Sent message: {message}')
        response = await websocket.recv()
        print(f'Received response: {response}')

asyncio.get_event_loop().run_until_complete(send_message())

这个简单的WebSocket客户端连接服务器,发送一条消息,并接收服务器的响应。

12. 实战案例:实时聊天应用

接下来,我们将创建一个简单的实时聊天应用,包括一个WebSocket服务器和多个客户端。

(1) 创建WebSocket服务器

import asyncio
import websockets

connected_clients = set()

async def broadcast(message):
    if connected_clients:
        await asyncio.wait([client.send(message) for client in connected_clients])

async def chat(websocket, path):
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            print(f'Received message: {message}')
            await broadcast(message)
    finally:
        connected_clients.remove(websocket)

# 创建 WebSocket 服务器
start_server = websockets.serve(chat, 'localhost', 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

这个WebSocket服务器监听8765端口,并将所有客户端的消息广播给其他客户端。

(2) 创建WebSocket客户端

import asyncio
import websockets

async def chat_client():
    uri = 'ws://localhost:8765'
    async with websockets.connect(uri) as websocket:
        while True:
            message = input('Enter your message: ')
            await websocket.send(message)
            print('Sent message:', message)
            response = await websocket.recv()
            print('Received response:', response)

asyncio.get_event_loop().run_until_complete(chat_client())

这个WebSocket客户端连接服务器,发送消息,并接收服务器的广播消息。

责任编辑:赵宁宁 来源: 小白PythonAI编程
相关推荐

2020-02-07 09:59:29

Python异常处理语言

2020-10-14 10:50:50

SpringSessiJavaweb

2019-10-24 09:09:28

MySQLACIDJava

2021-04-13 08:25:12

测试开发Java注解Spring

2023-12-22 15:32:20

2021-04-19 08:35:44

PythonPython语言Python基础

2020-09-25 16:52:57

Python

2022-08-16 15:17:37

机器学习算法模型

2024-11-06 17:00:34

Python嵌入式系统编程

2022-08-01 07:42:17

线程安全场景

2009-08-02 21:47:35

安防线缆

2020-10-07 15:15:41

Python

2021-04-29 10:01:30

JavaMathJava编程

2019-07-26 11:27:25

MySQLSQL数据库

2021-01-15 08:35:49

Zookeeper

2018-01-29 15:23:14

网络知识点软件测试

2024-09-09 23:15:55

2023-05-23 22:19:04

索引MySQL优化

2010-08-17 14:56:00

HCNE认证

2011-04-15 12:25:21

BGP路由
点赞
收藏

51CTO技术栈公众号