http、https、websocket

概念解析

HTTP(超文本传输协议)是一种无状态的请求/响应协议,通常用于客户端(如Web浏览器)和服务器之间的通信。客户端发送一个请求到服务器,然后服务器返回一个响应。HTTPS是HTTP的安全版本,它在HTTP的基础上通过SSL/TLS提供了数据加密。

WebSocket协议提供了在客户端和服务器之间的持久连接上进行全双工通信的能力。这意味着服务器可以在任何时候发送消息给客户端,而不需要客户端先发起请求,这对于需要实时更新的应用程序(如在线游戏、聊天应用等)非常有用。

要运行这些示例,请确保你已经安装了必要的库:

bash 复制代码
pip install requests websocket-client

HTTP 示例程序

这个程序将发送一个GET请求到 `httpbin.org`,这是一个用于测试HTTP请求和响应的服务。

python 复制代码
import requests

def http_get_example():
    url = 'https://httpbin.org/get'
    response = requests.get(url)
    print("HTTP GET Response:")
    print(response.json())  # 打印JSON响应的内容

# 运行HTTP示例
http_get_example()

HTTPS 示例程序

HTTPS与HTTP在代码层面上几乎是相同的,`requests` 库会自动处理HTTPS连接的加密。这里我们使用相同的服务,但是通过HTTPS进行通信。

python 复制代码
def https_get_example():
    url = 'https://httpbin.org/get'
    response = requests.get(url)
    print("HTTPS GET Response:")
    print(response.json())  # 打印JSON响应的内容

# 运行HTTPS示例
https_get_example()

WebSocket 示例程序

这个程序将连接到 `websocket.org` 的测试服务器,并发送一个消息,然后接收回声消息。

python 复制代码
import websocket
import _thread
import time

def on_message(ws, message):
    print("WebSocket Message Received:")
    print(message)
    ws.close()

def on_error(ws, error):
    print("WebSocket Error:", error)

def on_close(ws, close_status_code, close_msg):
    print("WebSocket Connection Closed")

def on_open(ws):
    def run(*args):
        time.sleep(1)
        ws.send("Hello, WebSocket!")
    _thread.start_new_thread(run, ())

def websocket_example():
    ws = websocket.WebSocketApp("wss://echo.websocket.org",
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.run_forever()

# 运行WebSocket示例
websocket_example()

在这些示例中,HTTP和HTTPS程序演示了如何使用请求/响应模型进行通信,而WebSocket程序演示了如何建立持久的全双工通信连接。

然后,将上述代码片段保存到一个`.py`文件中,并运行它。每个函数将演示其对应协议的核心通信功能。

相关推荐
一只小鱼儿吖1 小时前
进程代理单窗口单IP技术:原理、应用与实现
网络·网络协议·tcp/ip
稳联技术1 小时前
Ethernet IP与Profinet共舞:网关驱动绿色工业的智慧脉动
网络·网络协议·tcp/ip
学习3人组1 小时前
CentOS配置网络
linux·网络·centos
隆里卡那唔1 小时前
在dify中通过http请求neo4j时为什么需要将localhost变为host.docker.internal
http·docker·neo4j
高兴达2 小时前
RPC框架--实现一个非常简单的RPC调用
网络协议·rpc·firefox
~山有木兮2 小时前
LiteHub中间件之限流实现
网络·http·中间件
cui_win2 小时前
【网络】Linux 内核优化实战 - net.core.flow_limit_table_len
linux·运维·网络
BD_Marathon3 小时前
虚拟机网络检查
网络
游戏开发爱好者83 小时前
iOS App首次启动请求异常调试:一次冷启动链路抓包与初始化流程修复
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915106323 小时前
频繁迭代下完成iOS App应用上架App Store:一次快速交付项目的完整回顾
websocket·网络协议·tcp/ip·http·网络安全·https·udp