fix: fixing sudden disconnect for multiple connection

This commit is contained in:
2025-10-27 13:09:16 +07:00
parent b71e8121e2
commit 49a30d3b44
5 changed files with 62 additions and 38 deletions

View File

@@ -1,9 +1,11 @@
package internal
import (
"fmt"
"log"
"time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
)
@@ -14,6 +16,7 @@ const (
)
type Client struct {
ID string
Conn *websocket.Conn
Send chan []byte
SubscribedPath string
@@ -22,8 +25,9 @@ type Client struct {
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
return &Client{
ID: uuid.NewString(),
Conn: conn,
Send: make(chan []byte, 2),
Send: make(chan []byte, 1),
SubscribedPath: subscribedPath,
done: make(chan struct{}, 1),
}
@@ -41,7 +45,7 @@ func NewHub() *Hub {
Broadcast: make(chan []byte, 1),
Register: make(chan *Client, 1),
Unregister: make(chan *Client, 1),
Clients: make(map[*Client]bool, 0),
Clients: make(map[*Client]bool),
}
}
@@ -53,19 +57,21 @@ func (h *Hub) Run() {
h.Clients[client] = true
log.Println("Client registered")
case c := <-h.Unregister:
if _, ok := h.Clients[c]; ok {
if v, ok := h.Clients[c]; ok {
fmt.Println(v, c)
delete(h.Clients, c)
close(c.Send)
}
log.Println("Client Unregistered")
case message := <-h.Broadcast:
for client := range h.Clients {
select {
case client.Send <- message:
default:
close(client.Send)
delete(h.Clients, client)
}
client.Send <- message
// select {
// case client.Send <- message:
// default:
// close(client.Send)
// delete(h.Clients, client)
// }
}
}
}
@@ -86,15 +92,18 @@ func WritePump(c *Client, h *Hub) {
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.Conn.WriteMessage(websocket.CloseMessage, []byte{})
fmt.Println(ok)
return
}
if err := c.Conn.WriteMessage(websocket.TextMessage, message); err != nil {
fmt.Println(err)
return
}
case <-pingTicker.C:
c.Conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
fmt.Println(err)
return
}
}
@@ -107,7 +116,7 @@ func ReadPump(c *Client, h *Hub) {
c.Conn.Close()
}()
c.Conn.SetReadLimit(512)
c.Conn.SetReadLimit(1024)
c.Conn.SetReadDeadline(time.Now().Add(pongWait))
c.Conn.SetPongHandler(func(string) error {
c.Conn.SetReadDeadline(time.Now().Add(pongWait))