[BUGFIX] review 1 - locking
This commit is contained in:
parent
b20c614a69
commit
83c721ba4d
|
@ -8,6 +8,7 @@ package socket
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/FreifunkBremen/yanic/database"
|
"github.com/FreifunkBremen/yanic/database"
|
||||||
|
@ -18,6 +19,7 @@ type Connection struct {
|
||||||
database.Connection
|
database.Connection
|
||||||
listener net.Listener
|
listener net.Listener
|
||||||
clients map[net.Addr]net.Conn
|
clients map[net.Addr]net.Conn
|
||||||
|
clientMux sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
@ -56,8 +58,10 @@ func (conn *Connection) PruneNodes(deleteAfter time.Duration) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *Connection) Close() {
|
func (conn *Connection) Close() {
|
||||||
|
conn.clientMux.Lock()
|
||||||
for _, c := range conn.clients {
|
for _, c := range conn.clients {
|
||||||
c.Close()
|
c.Close()
|
||||||
}
|
}
|
||||||
|
conn.clientMux.Unlock()
|
||||||
conn.listener.Close()
|
conn.listener.Close()
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,18 +11,21 @@ type EventMessage struct {
|
||||||
Body interface{} `json:"body,omitempty"`
|
Body interface{} `json:"body,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (config *Connection) handleSocketConnection(ln net.Listener) {
|
func (conn *Connection) handleSocketConnection(ln net.Listener) {
|
||||||
for {
|
for {
|
||||||
c, err := ln.Accept()
|
c, err := ln.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("[socket-database] error during connection of a client", err)
|
log.Println("[socket-database] error during connection of a client", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
config.clients[c.RemoteAddr()] = c
|
conn.clientMux.Lock()
|
||||||
|
conn.clients[c.RemoteAddr()] = c
|
||||||
|
conn.clientMux.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *Connection) sendJSON(msg EventMessage) {
|
func (conn *Connection) sendJSON(msg EventMessage) {
|
||||||
|
conn.clientMux.Lock()
|
||||||
for addr, c := range conn.clients {
|
for addr, c := range conn.clients {
|
||||||
d := json.NewEncoder(c)
|
d := json.NewEncoder(c)
|
||||||
|
|
||||||
|
@ -33,4 +36,5 @@ func (conn *Connection) sendJSON(msg EventMessage) {
|
||||||
delete(conn.clients, addr)
|
delete(conn.clients, addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
conn.clientMux.Unlock()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue