logo
0
0
Login
Zhang Wenhu<wenhulove333@163.com>
first commit

WebSocket代理系统

这是一个用Golang实现的WebSocket代理系统,支持客户端ID代理转发和反向HTTP请求功能。

功能特性

  • ✅ WebSocket服务端和客户端
  • ✅ 服务端提供HTTP服务
  • ✅ 客户端ID代理转发机制
  • ✅ 反向HTTP请求功能
  • ✅ 客户端连接管理
  • ✅ 请求-响应匹配机制

系统架构

┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ │ HTTP客户端 │───▶│ WebSocket服务端 │◀───│ WebSocket客户端 │ │ │ │ │ │ │ │ 发起HTTP请求 │ │ 管理客户端连接 │ │ 执行实际HTTP请求 │ │ /proxy/{id}/... │ │ 转发请求/响应 │ │ 返回HTTP响应 │ └─────────────────┘ └──────────────────┘ └─────────────────┘

快速开始

1. 安装依赖

go mod tidy

2. 启动服务端

使用PowerShell:

.\scripts\start_server.ps1

或使用CMD:

.\scripts\start_server.bat

或直接运行:

go run cmd/server/main.go -port 8080

3. 启动客户端

使用PowerShell:

.\scripts\start_client.ps1

或使用CMD:

.\scripts\start_client.bat

或直接运行:

go run cmd/client/main.go -server localhost:8080 -id my-client-001

API接口

1. 代理HTTP请求

通过WebSocket客户端代理HTTP请求:

# 格式: /proxy/{client_id}/{target_url} curl -X GET http://localhost:8080/proxy/my-client-001/httpbin.org/get curl -X POST http://localhost:8080/proxy/my-client-001/httpbin.org/post -d '{"key":"value"}'

2. 反向HTTP请求

服务端主动发起HTTP请求:

curl -X POST http://localhost:8080/api/reverse-http \ -H "Content-Type: application/json" \ -d '{ "client_id": "my-client-001", "method": "GET", "url": "http://httpbin.org/get" }'

3. 列出连接的客户端

curl http://localhost:8080/api/clients

4. 健康检查

curl http://localhost:8080/health

配置说明

服务端配置 (configs/server_config.json)

{ "server": { "port": 8080, "host": "localhost" }, "websocket": { "max_clients": 100, "read_timeout": 60, "write_timeout": 10 }, "http": { "proxy_timeout": 10, "max_body_size": 10485760 } }

客户端配置 (configs/client_config.json)

{ "client": { "server_url": "localhost:8080", "client_id": "my-client-001", "reconnect_interval": 5 }, "http": { "timeout": 30, "max_redirects": 10 } }

消息协议

消息类型

  • register - 客户端注册
  • http_request - HTTP请求
  • http_response - HTTP响应
  • reverse_http - 反向HTTP请求

消息格式

{ "type": "http_request", "client_id": "my-client-001", "data": { "method": "GET", "url": "http://httpbin.org/get", "headers": {"Content-Type": "application/json"}, "body": "{}" }, "id": "1234567890" }

项目结构

websocket-proxy/ ├── cmd/ │ ├── server/ # 服务端入口 │ └── client/ # 客户端入口 ├── internal/ │ ├── server/ # 服务端核心逻辑 │ ├── client/ # 客户端核心逻辑 │ └── common/ # 通用类型定义 ├── configs/ # 配置文件 ├── scripts/ # 启动脚本 └── README.md

开发说明

构建项目

# 构建服务端 go build -o bin/server cmd/server/main.go # 构建客户端 go build -o bin/client cmd/client/main.go

运行测试

# 启动服务端 ./bin/server -port 8080 # 启动客户端 ./bin/client -server localhost:8080 -id test-client

故障排除

常见问题

  1. 客户端连接失败

    • 检查服务端是否正在运行
    • 确认端口号是否正确
    • 检查防火墙设置
  2. 代理请求超时

    • 检查客户端是否在线
    • 确认目标URL是否可达
    • 调整超时时间配置
  3. WebSocket连接断开

    • 检查网络连接
    • 确认服务端负载是否过高
    • 查看日志文件获取详细信息

日志查看

服务端和客户端都会输出详细的日志信息,包括连接状态、请求处理情况和错误信息。

许可证

MIT License