package main

import (
	"fmt"
	"log"
	"net/http"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

// 服务器的 WebSocket URL 和 token
var wsBaseURL = "ws://localhost:8099/WorldChats/ws?worldId=93&AuthId=fc9058b44f7850b4438afb11033891ab"
var token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3Mjk1MjI2MzksImxldmVsIjowLCJ1c2VyX2lkIjo1ODV9.rqUCi2qpJ8knLlaguvn9k5ES_fWREfKJjqhiYeNNaiM"

// WebSocket 连接的客户端函数
func connectToWebSocket(wg *sync.WaitGroup, uid int) {
	defer wg.Done()

	// 构造 WebSocket URL，使用不同的 uid
	wsURL := fmt.Sprintf("%s&uid=%d", wsBaseURL, uid)

	// 设置请求头，包括 Token
	header := http.Header{}
	header.Add("Token", token1)

	// 建立 WebSocket 连接
	conn, _, err := websocket.DefaultDialer.Dial(wsURL, header)
	if err != nil {
		log.Printf("用户 %d: 无法连接到服务器: %v\n", uid, err)
		return
	}
	defer conn.Close()

	// 向服务器发送测试消息
	message := fmt.Sprintf("Hello from client %d", uid)
	err = conn.WriteMessage(websocket.TextMessage, []byte(message))
	if err != nil {
		log.Printf("用户 %d: 发送消息失败: %v\n", uid, err)
		return
	}

	// 读取服务器的回复
	_, reply, err := conn.ReadMessage()
	if err != nil {
		log.Printf("用户 %d: 读取消息失败: %v\n", uid, err)
		return
	}
	log.Printf("用户 %d: 收到服务器回复: %s\n", uid, string(reply))
}

func main() {
	// 并发连接的用户 uid 从 634 到 741
	startUID := 634
	endUID := 741

	var wg sync.WaitGroup

	// 启动并发的 WebSocket 连接
	for uid := startUID; uid <= endUID; uid++ {
		wg.Add(1)
		go connectToWebSocket(&wg, uid)
		time.Sleep(10 * time.Millisecond) // 避免瞬时过多请求，可以根据需要调整或去掉
	}

	// 等待所有连接完成
	wg.Wait()
	log.Printf("所有用户 (%d 到 %d) 的 WebSocket 连接测试已完成\n", startUID, endUID)
}
