跳到主要内容

使用python 和 golang 测试10000个websocket连接

· 阅读需 1 分钟
forkp

使用Python和Golang测试10000个连接

python

import asyncio
import websockets

async def connect(uri):
async with websockets.connect(uri) as websocket:
# 在这里可以发送和接收消息
await websocket.send("Hello")
response = await websocket.recv()
print(response)

async def main():
uri = "ws://localhost:3322"
tasks = [connect(uri) for _ in range(10000)]
await asyncio.gather(*tasks)

asyncio.run(main())

go

package main

import (
"log"
"sync"
"time"
"golang.org/x/net/websocket"
)

const numConnections = 10000

func connect(uri string, wg *sync.WaitGroup) {
defer wg.Done()
ws, err := websocket.Dial(uri, "", "http://localhost/")
if err != nil {
log.Println("Failed to connect:", err)
return
}
defer ws.Close()

// 发送和接收消息
_, err = ws.Write([]byte("Hello"))
if err != nil {
log.Println("Failed to send message:", err)
return
}

var msg = make([]byte, 512)
_, err = ws.Read(msg)
if err != nil {
log.Println("Failed to read message:", err)
return
}
log.Println("Received message:", string(msg))
}

func main() {
uri := "ws://localhost:3322"
var wg sync.WaitGroup

for i := 0; i < numConnections; i++ {
wg.Add(1)
go connect(uri, &wg)
time.Sleep(time.Millisecond) // 控制连接创建速率
}

wg.Wait()
}