clean wsClients and update buffer size

This commit is contained in:
poiuty 2023-07-03 22:53:36 +03:00
parent e0d1877fb9
commit 2e7720d6d3
2 changed files with 15 additions and 12 deletions

View file

@ -2,11 +2,12 @@ package main
import ( import (
"fmt" "fmt"
jsoniter "github.com/json-iterator/go"
"io" "io"
"log" "log"
"net" "net"
"os" "os"
jsoniter "github.com/json-iterator/go"
) )
func removeSocket(s string) { func removeSocket(s string) {

View file

@ -3,8 +3,8 @@ package main
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"time"
"runtime" "runtime"
"time"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
@ -25,9 +25,9 @@ var (
Add chan *Client Add chan *Client
Del chan *Client Del chan *Client
}{ }{
Broadcast: make(chan []byte, 100), Broadcast: make(chan []byte, 1),
Add: make(chan *Client, 100), Add: make(chan *Client),
Del: make(chan *Client, 100), Del: make(chan *Client),
} }
upgrader = websocket.Upgrader{ upgrader = websocket.Upgrader{
@ -44,7 +44,7 @@ var (
) )
func broadcast() { func broadcast() {
ticker := time.NewTicker(30 * time.Second) ticker := time.NewTicker(20 * time.Second)
for { for {
select { select {
case client := <-ws.Add: case client := <-ws.Add:
@ -54,10 +54,11 @@ func broadcast() {
delete(wsClients, conn) delete(wsClients, conn)
case r := <-ws.Broadcast: case r := <-ws.Broadcast:
//fmt.Println(len(ws.Broadcast), cap(ws.Broadcast))
sendBroadcast(r) sendBroadcast(r)
case <-ticker.C: case <-ticker.C:
fmt.Println("WebSocket:", len(wsClients), "Goroutines:", runtime.NumGoroutine()) fmt.Println(len(wsClients), runtime.NumGoroutine(), len(ws.Broadcast), cap(ws.Broadcast))
} }
} }
} }
@ -75,6 +76,7 @@ func sendBroadcast(message []byte) {
continue continue
} }
if err := client.Conn.WriteMessage(1, message); err != nil { if err := client.Conn.WriteMessage(1, message); err != nil {
delete(wsClients, client)
client.Conn.Close() client.Conn.Close()
} }
} }