Skip to content

Instantly share code, notes, and snippets.

@M0nteCarl0
Created July 28, 2023 08:44
Show Gist options
  • Save M0nteCarl0/21697fd6da6f8c31e7f6ca4ef0438055 to your computer and use it in GitHub Desktop.
Save M0nteCarl0/21697fd6da6f8c31e7f6ca4ef0438055 to your computer and use it in GitHub Desktop.
ActiveConnection storage
package main
import (
"fmt"
"net"
"sync"
)
type ActiveConnection struct {
conn net.Conn
// Дополнительные поля, если необходимо
}
type ActiveConnections struct {
connections []*ActiveConnection
mutex sync.Mutex
}
func (ac *ActiveConnections) Add(conn net.Conn) {
ac.mutex.Lock()
defer ac.mutex.Unlock()
activeConn := &ActiveConnection{
conn: conn,
// Инициализация дополнительных полей
}
ac.connections = append(ac.connections, activeConn)
}
func (ac *ActiveConnections) Remove(conn net.Conn) {
ac.mutex.Lock()
defer ac.mutex.Unlock()
for i, activeConn := range ac.connections {
if activeConn.conn == conn {
ac.connections = append(ac.connections[:i], ac.connections[i+1:]...)
return
}
}
}
func handleConnection(conn net.Conn, activeConns *ActiveConnections) {
// Обработка соединения
defer conn.Close()
activeConns.Remove(conn)
}
func main() {
listener, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println("Ошибка при запуске сервера:", err)
return
}
activeConns := &ActiveConnections{}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Ошибка при принятии соединения:", err)
continue
}
activeConns.Add(conn)
go handleConnection(conn, activeConns)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment