Compare commits

...

3 commits

Author SHA1 Message Date
f8a047abdf feat: update logging for client connect and disconnect
- update logging to use ws.RemoteAddr()

🤖
2024-10-30 10:19:07 +01:00
89751ee7ea feat: update client management
- change Clients map to use net.Addr as the key type
- update `HandleConnection()` to store clients using LocalAddr
- modify `handleClientCommands()` to delete clients by LocalAddr

🤖
2024-10-30 10:17:24 +01:00
ebb58a4489 feat: rename Client model to WebsocketClient
🤖
2024-10-30 09:57:09 +01:00
3 changed files with 11 additions and 10 deletions

View file

@ -10,15 +10,15 @@ import (
)
// Listens for commands from a client and handles them
func handleClientCommands(c models.Client) {
func handleClientCommands(c models.WebsocketClient) {
ws := c.Conn
for {
var clientCommand models.ClientCommand
_, message, err := ws.ReadMessage()
if err != nil {
log.Info("Client disconnected:", "msg", err, "host", ws.NetConn().RemoteAddr(), "clients", len(Clients)-1)
delete(Clients, ws)
log.Info("Client disconnected:", "msg", err, "host", ws.RemoteAddr(), "clients", len(Clients)-1)
delete(Clients, ws.LocalAddr())
break
}

View file

@ -3,14 +3,15 @@ package websocket
import (
"github.com/charmbracelet/log"
"github.com/gorilla/websocket"
"net"
"net/http"
"sync"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
)
// Clients is a map of connected WebSocket clients, where each client is represented by the Client struct
var Clients = make(map[*websocket.Conn]*models.Client)
// Clients is a map of connected WebSocket clients, where each client is represented by the WebsocketClient struct
var Clients = make(map[net.Addr]*models.WebsocketClient)
var mu sync.Mutex // Mutex to protect access to the Clients map
// Upgrade HTTP requests to WebSocket connections
@ -28,14 +29,14 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
}
defer ws.Close()
log.Info("Client connected", "host", ws.NetConn().RemoteAddr(), "clients", len(Clients)+1)
log.Info("Client connected", "host", ws.RemoteAddr(), "clients", len(Clients)+1)
// Register the new client
client := models.Client{
client := models.WebsocketClient{
Conn: ws,
}
mu.Lock()
Clients[ws] = &client
Clients[ws.LocalAddr()] = &client
mu.Unlock()
// Listen for commands from the connected client

View file

@ -13,13 +13,13 @@ type ClientCommand struct {
}
// Represents a single client
type Client struct {
type WebsocketClient struct {
Conn *websocket.Conn
}
// Sends a message to the websocket.
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
func (c *Client) SendMessage(messageType int, data []byte) error {
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
err := c.Conn.WriteMessage(messageType, data)
if err != nil {
log.Error("Error writing to WebSocket:", "msg", err)