1 package main 2 3 import ( 4 "net" 5 "sync" 6 "encoding/json" 7 ) 8 9 func 10 main() { 11 12 connection s := map[ net.Conn ] interface{} {} 13 mutex := sync.RWMutex{} 14 15 broadcaste r := make( chan interface{} ) 16 go func() { 17 for { 18 data, _ := json.Marshal( <- broadcaste r ) 19 mutex.RLock() 20 conns := connection s 21 mutex.RUnlock() 22 for conn, _ := range conns { conn.Write( data ) } 23 } 24 }() 25 26 listener, _ := net.Listen( "tcp", ":6666" ) 27 defer listener.Close() 28 for { 29 conn, _ := listener.Accept() 30 mutex.Lock() 31 connection s[ conn ] = "" 32 mutex.Unlock() 33 go func() { 34 decoder := json.NewDecoder ( conn ) 35 for { 36 var w interface{} 37 err := decoder.Decode( &w ) 38 if err != nil { break } 39 broadcaste r <- w 40 } 41 mutex.Lock() 42 delete( connection s, conn ) 43 mutex.Unlock() 44 conn.Close() 45 }() 46 } 47 }
posted by
Saturn
on Wed 24 Dec 2014
at 22:07