[BUGFIX] review 1 - locking

This commit is contained in:
Martin Geno 2017-04-27 22:44:06 +02:00
parent b20c614a69
commit 83c721ba4d
No known key found for this signature in database
GPG Key ID: F0D39A37E925E941
2 changed files with 12 additions and 4 deletions

View File

@ -8,6 +8,7 @@ package socket
import (
"log"
"net"
"sync"
"time"
"github.com/FreifunkBremen/yanic/database"
@ -18,6 +19,7 @@ type Connection struct {
database.Connection
listener net.Listener
clients map[net.Addr]net.Conn
clientMux sync.Mutex
}
func init() {
@ -56,8 +58,10 @@ func (conn *Connection) PruneNodes(deleteAfter time.Duration) {
}
func (conn *Connection) Close() {
conn.clientMux.Lock()
for _, c := range conn.clients {
c.Close()
}
conn.clientMux.Unlock()
conn.listener.Close()
}

View File

@ -11,18 +11,21 @@ type EventMessage struct {
Body interface{} `json:"body,omitempty"`
}
func (config *Connection) handleSocketConnection(ln net.Listener) {
func (conn *Connection) handleSocketConnection(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
log.Println("[socket-database] error during connection of a client", err)
continue
}
config.clients[c.RemoteAddr()] = c
conn.clientMux.Lock()
conn.clients[c.RemoteAddr()] = c
conn.clientMux.Unlock()
}
}
func (conn *Connection) sendJSON(msg EventMessage) {
conn.clientMux.Lock()
for addr, c := range conn.clients {
d := json.NewEncoder(c)
@ -33,4 +36,5 @@ func (conn *Connection) sendJSON(msg EventMessage) {
delete(conn.clients, addr)
}
}
conn.clientMux.Unlock()
}