modify websocketserver to broker with callback functions
This commit is contained in:
73
websocket/clientHandler.go
Normal file
73
websocket/clientHandler.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
|
||||
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
||||
)
|
||||
|
||||
// serves as connection handler of websocket
|
||||
type ClientHandler struct {
|
||||
sync.RWMutex
|
||||
Clients models.Clients
|
||||
}
|
||||
|
||||
// initaiates new conections with client map
|
||||
func NewConnectionHandler() *ClientHandler {
|
||||
return &ClientHandler{
|
||||
Clients: make(models.Clients),
|
||||
}
|
||||
}
|
||||
|
||||
// Connect a recieving websocket connection
|
||||
func (cH *ClientHandler) ConnectNewClient(id string, c *gin.Context) (client *models.Client, err error) {
|
||||
if _, exists := cH.Clients[id]; exists {
|
||||
return cH.Clients[id], nil
|
||||
}
|
||||
|
||||
client, err = models.ConnectNewClient(id, c)
|
||||
client.OnClose = func(code int, reason string) {
|
||||
delete(cH.Clients, id)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cH.Lock()
|
||||
cH.Clients[id] = client
|
||||
cH.Unlock()
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// get client client
|
||||
func (c *ClientHandler) GetClient(id string) *wsModels.Client {
|
||||
if client, ok := c.Clients[id]; ok {
|
||||
return client
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sends json response to client
|
||||
func (c *ClientHandler) SendResponse(id string, r *json_dataModels.Response) error {
|
||||
client, ok := c.Clients[id]
|
||||
if !ok {
|
||||
return fmt.Errorf("client not found for id %s", id)
|
||||
|
||||
}
|
||||
b, err := json.Marshal(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := client.SendResponse(b, 5); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user