• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Python实现常见网络通信的示例详解

    发布者: 天下网吧 | 发布时间: 2025-6-17 08:14| 查看数: 45| 评论数: 0|帖子模式

    一、HTTP/HTTPS 通信


    1. 客户端示例(requests 库)
    1. import requests

    2. # HTTP GET
    3. response = requests.get('http://httpbin.org/get')
    4. print(response.text)

    5. # HTTPS POST
    6. response = requests.post(
    7.     'https://httpbin.org/post',
    8.     data={'key': 'value'},
    9.     verify=True  # 验证 SSL 证书(默认)
    10. )
    11. print(response.json())
    复制代码
    2. 服务端示例(Flask)
    1. from flask import Flask, request

    2. app = Flask(__name__)

    3. @app.route('/api', methods=['GET', 'POST'])
    4. def handle_request():
    5.     if request.method == 'GET':
    6.         return {'message': 'GET received'}
    7.     elif request.method == 'POST':
    8.         return {'data': request.json}

    9. if __name__ == '__main__':
    10.     app.run(ssl_context='adhoc')  # 启用 HTTPS
    复制代码
    二、UDP 通信



    1. 服务端
    1. import socket

    2. server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    3. server.bind(('0.0.0.0', 9999))

    4. while True:
    5.     data, addr = server.recvfrom(1024)
    6.     print(f"Received from {addr}: {data.decode()}")
    7.     server.sendto(b'UDP response', addr)
    复制代码


    2. 客户端
    1. import socket

    2. client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    3. client.sendto(b'Hello UDP', ('localhost', 9999))
    4. response, addr = client.recvfrom(1024)
    5. print(f"Received: {response.decode()}")
    复制代码
    三、WebSocket 通信

    需要安装库:
    1. pip install websockets
    复制代码
    1. 服务端
    1. import asyncio
    2. import websockets

    3. async def handler(websocket):
    4.     async for message in websocket:
    5.         print(f"Received: {message}")
    6.         await websocket.send(f"Echo: {message}")

    7. async def main():
    8.     async with websockets.serve(handler, "localhost", 8765):
    9.         await asyncio.Future()  # 永久运行

    10. asyncio.run(main())
    复制代码
    2. 客户端
    1. import asyncio
    2. import websockets

    3. async def client():
    4.     async with websockets.connect("ws://localhost:8765") as ws:
    5.         await ws.send("Hello WebSocket!")
    6.         response = await ws.recv()
    7.         print(f"Received: {response}")

    8. asyncio.run(client())
    复制代码
    四、Server-Sent Events (SSE)

    需要安装库:
    1. pip install sseclient-py
    复制代码

    1. 服务端(Flask 实现)
    1. from flask import Flask, Response

    2. app = Flask(__name__)

    3. @app.route('/stream')
    4. def stream():
    5.     def event_stream():
    6.         for i in range(5):
    7.             yield f"data: Message {i}\n\n"
    8.     return Response(event_stream(), mimetype="text/event-stream")

    9. if __name__ == '__main__':
    10.     app.run()
    复制代码
    2. 客户端
    1. import requests
    2. from sseclient import SSEClient

    3. url = 'http://localhost:5000/stream'
    4. response = requests.get(url, stream=True)
    5. client = SSEClient(response)

    6. for event in client.events():
    7.     print(f"Received event: {event.data}")
    复制代码
    关键点说明


    • HTTP/HTTPS:最常用的请求-响应模型
    • UDP:无连接协议,适合实时性要求高的场景
    • WebSocket:全双工通信协议,适合实时双向通信
    • SSE:服务器到客户端的单向推送技术
    • 安全建议

      • HTTPS 使用 requests 的
        1. verify=True
        复制代码
        验证证书
      • WebSocket 使用
        1. wss://
        复制代码
        安全协议
      • 生产环境应使用正式 SSL 证书

    根据具体需求选择协议:

    • 简单数据请求:HTTP/HTTPS
    • 实时游戏/视频:UDP
    • 聊天应用:WebSocket
    • 实时通知:SSE
    建议根据实际场景配合使用异步框架(如 aiohttp、FastAPI)以获得更好的性能。
    到此这篇关于Python实现常见网络通信的示例详解的文章就介绍到这了,更多相关Python网络通信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/python/3398112xz.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表