websocket学习

是的,上述提供的代码示例支持在建立WebSocket连接后手动输入信息并传递给服务端。无论你选择使用 websockets 库(基于 asyncio)还是 websocket-client 库(基于多线程),都可以在连接建立后通过命令行手动输入消息发送给服务器,并接收服务器返回的消息。

为了确保你能够顺利地手动发送和接收消息,以下是对两种方法的进一步说明和完整的示例代码。这些代码已经集成了手动输入发送消息的功能,并在连接建立后提示用户输入消息。


方法一:使用 websockets 库(基于 asyncio

完整示例代码

import asyncio
import websockets

async def websocket_client(uri, token, params=None):
    # 构建查询参数字符串(如果有参数需要传递)
    if params:
        query_string = "&".join([f"{key}={value}" for key, value in params.items()])
        full_uri = f"{uri}?{query_string}"
    else:
        full_uri = uri

    # 构建头部信息,包括Authorization token
    headers = {
        "Authorization": f"Bearer {token}"
    }

    try:
        # 建立WebSocket连接
        async with websockets.connect(full_uri, extra_headers=headers) as websocket:
            print("已连接到WebSocket服务器。你可以开始发送消息。输入 'exit' 退出。")

            async def send_messages():
                while True:
                    message = await asyncio.get_event_loop().run_in_executor(None, input, "> ")
                    if message.lower() == "exit":
                        await websocket.close()
                        print("连接已关闭。")
                        break
                    await websocket.send(message)

            async def receive_messages():
                try:
                    async for message in websocket:
                        print(f"来自服务器的消息: {message}")
                except websockets.exceptions.ConnectionClosed:
                    print("连接已关闭。")

            # 并行运行发送和接收消息的任务
            await asyncio.gather(send_messages(), receive_messages())

    except Exception as e:
        print(f"连接失败: {e}")

if __name__ == "__main__":
    # 配置WebSocket的URI
    ws_uri = "ws://localhost:8000/ws/your_endpoint"  # 替换为你的WebSocket地址

    # 设置需要传递的参数(如果有)
    parameters = {
        "param1": "value1",
        "param2": "value2"
        # 根据需要添加其他参数
    }

    # 设置token
    auth_token = "your_token_here"  # 替换为你的token

    # 运行客户端
    asyncio.run(websocket_client(ws_uri, auth_token, parameters))

使用说明

  1. 安装依赖库

    确保你已经安装了 websockets 库:

    pip install websockets
    
  2. 配置参数

    • ws_uri 替换为你的WebSocket服务器地址。
    • 根据需要设置 parameters 字典中的参数。
    • auth_token 替换为你的实际token。
  3. 运行客户端

    运行脚本后,终端会显示提示信息:

    已连接到WebSocket服务器。你可以开始发送消息。输入 'exit' 退出。
    > 
    

    你可以在提示符 > 后输入消息,这些消息将通过WebSocket发送到服务器。输入 exit 将关闭连接。

  4. 接收消息

    当服务器发送消息时,客户端会在终端显示:

    来自服务器的消息: 服务器返回的内容
    

功能确认

  • 手动发送消息:通过 input 函数实现,用户可以在命令行中输入任意消息并发送到服务器。
  • 接收服务器消息:异步监听服务器发送的消息并在终端显示。
  • 关闭连接:输入 exit 命令后,客户端会优雅地关闭WebSocket连接。

方法二:使用 websocket-client 库(基于多线程)

完整示例代码

import websocket
import threading

def on_message(ws, message):
    print(f"来自服务器的消息: {message}")

def on_error(ws, error):
    print(f"错误: {error}")

def on_close(ws, close_status_code, close_msg):
    print("### 连接已关闭 ###")

def on_open(ws):
    print("已连接到WebSocket服务器。你可以开始发送消息。输入 'exit' 退出。")

    def run():
        while True:
            try:
                message = input("> ")
                if message.lower() == "exit":
                    ws.close()
                    print("连接正在关闭...")
                    break
                ws.send(message)
            except Exception as e:
                print(f"发送消息时发生错误: {e}")
                break

    # 启动一个新线程用于发送消息,避免阻塞
    thread = threading.Thread(target=run)
    thread.start()

if __name__ == "__main__":
    # 配置WebSocket的URI
    ws_uri = "ws://localhost:8000/ws/your_endpoint"  # 替换为你的WebSocket地址

    # 设置需要传递的参数(如果有)
    parameters = {
        "param1": "value1",
        "param2": "value2"
        # 根据需要添加其他参数
    }

    # 设置token
    auth_token = "your_token_here"  # 替换为你的token

    # 构建查询参数字符串(如果有参数需要传递)
    if parameters:
        query_string = "&".join([f"{key}={value}" for key, value in parameters.items()])
        full_uri = f"{ws_uri}?{query_string}"
    else:
        full_uri = ws_uri

    # 构建头部信息,包括Authorization token
    headers = {
        "Authorization": f"Bearer {auth_token}"
    }

    # 创建WebSocketApp实例,传递头部信息
    ws = websocket.WebSocketApp(full_uri,
                                header=headers,
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)

    # 运行WebSocket
    ws.run_forever()

使用说明

  1. 安装依赖库

    确保你已经安装了 websocket-client 库:

    pip install websocket-client
    
  2. 配置参数

    • ws_uri 替换为你的WebSocket服务器地址。
    • 根据需要设置 parameters 字典中的参数。
    • auth_token 替换为你的实际token。
  3. 运行客户端

    运行脚本后,终端会显示提示信息:

    已连接到WebSocket服务器。你可以开始发送消息。输入 'exit' 退出。
    > 
    

    你可以在提示符 > 后输入消息,这些消息将通过WebSocket发送到服务器。输入 exit 将关闭连接。

  4. 接收消息

    当服务器发送消息时,客户端会在终端显示:

    来自服务器的消息: 服务器返回的内容
    

功能确认

  • 手动发送消息:通过 input 函数实现,用户可以在命令行中输入任意消息并发送到服务器。
  • 接收服务器消息:通过回调函数 on_message 处理并显示服务器发送的消息。
  • 关闭连接:输入 exit 命令后,客户端会优雅地关闭WebSocket连接。

选择合适的方法

  • websockets

    • 优点
      • 基于异步编程,适合需要处理大量并发连接的场景。
      • 代码结构清晰,适合与其他 asyncio 代码集成。
    • 适用场景
      • 需要在异步环境中运行的应用。
      • 项目已经使用 asyncio 或需要高效的异步处理。
  • websocket-client

    • 优点
      • 基于多线程,适合同步编程环境。
      • 简单易用,适合快速开发和测试。
    • 适用场景
      • 简单的WebSocket客户端需求。
      • 项目主要采用同步编程,或不熟悉异步编程。

注意事项

  1. 认证方式一致性

    • 确保FastAPI后端的WebSocket认证方式与客户端一致。上述示例中,客户端通过 Authorization 头部传递Bearer token,后端应对应处理此认证方式。
  2. 安全性

    • 在生产环境中,建议使用 wss://(WebSocket Secure)协议,确保数据传输的安全性。
    • 确保token的安全传输和存储,避免泄露。
  3. 异常处理

    • 示例代码中包含了基本的异常处理,但在实际应用中,建议根据具体需求增强错误处理逻辑,例如重连机制、错误日志记录等。
  4. 环境准备

    • 确保你的FastAPI服务器已经启动,并且WebSocket端点配置正确,能够接收并处理客户端的连接和消息。

快速测试

为了快速测试上述客户端代码,你可以参考以下简单的FastAPI WebSocket服务端示例:

# server.py
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# 允许所有来源(仅用于测试,生产环境请根据需要配置)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.websocket("/ws/your_endpoint")
async def websocket_endpoint(websocket: WebSocket):
    # 认证处理
    token = websocket.headers.get("Authorization")
    if token != "Bearer your_token_here":
        await websocket.close(code=1008)  # Policy Violation
        return

    await websocket.accept()
    try:
        while True:
            data = await websocket.receive_text()
            print(f"收到客户端消息: {data}")
            await websocket.send_text(f"服务器已收到: {data}")
    except WebSocketDisconnect:
        print("客户端断开连接")

使用说明

  1. 安装依赖库

    pip install fastapi uvicorn
    
  2. 运行服务器

    uvicorn server:app --host 0.0.0.0 --port 8000
    
  3. 运行客户端

    使用前述提供的任一客户端代码,确保 auth_token 设置为 your_token_here,并连接到 ws://localhost:8000/ws/your_endpoint

  4. 测试通信

    • 在客户端输入消息,服务器将打印收到的消息,并回传确认消息。
    • 例如,客户端输入 Hello,服务器端控制台会显示 收到客户端消息: Hello,客户端会接收到 服务器已收到: Hello

通过上述步骤和代码示例,你可以轻松地使用Python客户端连接到基于FastAPI的WebSocket接口,手动发送和接收消息。如果你在实现过程中遇到任何问题,欢迎随时提问!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值