Add conns to server

This commit is contained in:
qowevisa 2024-06-09 07:38:31 +03:00
parent 1c5e2625d5
commit 5794814d9b
2 changed files with 49 additions and 0 deletions

46
cmd/server/conns.go Normal file
View File

@ -0,0 +1,46 @@
package main
import (
"log"
"net"
"sync"
)
var (
connCenter ConnCenter
)
type ConnCenter struct {
Conns map[uint16]net.Conn
Mu sync.Mutex
}
func (c *ConnCenter) Init() {
c.Conns = make(map[uint16]net.Conn)
}
func (c *ConnCenter) AddConn(id uint16, con net.Conn) (uint16, error) {
c.Mu.Lock()
defer c.Mu.Unlock()
log.Printf("Conns: add %v with %d id\n", con, id)
c.Conns[id] = con
return id, nil
}
func (c *ConnCenter) DeleteIfHaveOne(id uint16) {
name, found := c.Conns[id]
if !found {
log.Printf("Conn with %d id is not found; Can not delete\n", id)
return
}
delete(c.Conns, id)
log.Printf("Conn with %v con and %d id was found; Conn is deleted\n", name, id)
}
func (c *ConnCenter) GetConn(id uint16) (net.Conn, error) {
con, have := c.Conns[id]
if !have {
return nil, ERROR_DONT_HAVE
}
return con, nil
}

View File

@ -16,6 +16,7 @@ import (
func main() {
userCenter.Init()
linkCenter.Init()
connCenter.Init()
host, err := env.GetHost()
if err != nil {
log.Fatal(err)
@ -109,6 +110,7 @@ func handleClient(conn net.Conn) {
conn.Write(answ)
isRegistered = true
registeredID = id
connCenter.AddConn(id, conn)
}
case com.ID_CLIENT_SEND_SERVER_LINK:
l, err := com.DecodeLink(msg.Data)
@ -164,5 +166,6 @@ func handleClient(conn net.Conn) {
if isRegistered {
userCenter.DeleteIfHaveOne(registeredID)
linkCenter.CleanAfterLeave(registeredID)
connCenter.DeleteIfHaveOne(registeredID)
}
}