Хранилище handshaked соединений
This commit is contained in:
59
socket/connections.go
Normal file
59
socket/connections.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// Это хранилище для всех подключённых сокетов.
|
||||
// Оно обеспечивает потокобезопасный доступ к ним,
|
||||
// позволяя добавлять, удалять и получать сокеты без риска
|
||||
// гонок данных.
|
||||
|
||||
// Здесь содержатся только соединения прошедшие рукопожатие
|
||||
|
||||
type Connection struct {
|
||||
Identificator string
|
||||
//Подсоединенный сокет
|
||||
Socket *websocket.Conn
|
||||
}
|
||||
|
||||
// Потокобезопасное хранилище подключённых сокетов
|
||||
var (
|
||||
handshakeCompletedSockets = make(map[string]*Connection)
|
||||
socketsMutex = sync.RWMutex{}
|
||||
)
|
||||
|
||||
// Добавление сокета в хранилище
|
||||
func AddSocket(conn *Connection) {
|
||||
socketsMutex.Lock()
|
||||
defer socketsMutex.Unlock()
|
||||
handshakeCompletedSockets[conn.Identificator] = conn
|
||||
}
|
||||
|
||||
// Удаление сокета из хранилища
|
||||
func RemoveSocket(identificator string) {
|
||||
socketsMutex.Lock()
|
||||
defer socketsMutex.Unlock()
|
||||
delete(handshakeCompletedSockets, identificator)
|
||||
}
|
||||
|
||||
// Получение сокета по идентификатору
|
||||
func GetSocket(identificator string) (*Connection, bool) {
|
||||
socketsMutex.RLock()
|
||||
defer socketsMutex.RUnlock()
|
||||
conn, exists := handshakeCompletedSockets[identificator]
|
||||
return conn, exists
|
||||
}
|
||||
|
||||
// Получение всех сокетов
|
||||
func GetAllSockets() []*Connection {
|
||||
socketsMutex.RLock()
|
||||
defer socketsMutex.RUnlock()
|
||||
connections := make([]*Connection, 0, len(handshakeCompletedSockets))
|
||||
for _, conn := range handshakeCompletedSockets {
|
||||
connections = append(connections, conn)
|
||||
}
|
||||
return connections
|
||||
}
|
||||
Reference in New Issue
Block a user