Created
January 29, 2013 21:30
-
-
Save megakorre/4668073 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"io" | |
"net" | |
"os" | |
) | |
func echoLoop(c chan string,broadcast chan string, con net.Conn) { | |
rw := bufio.NewReadWriter( | |
bufio.NewReader(con), | |
bufio.NewWriter(io.MultiWriter(con, os.Stdout))) | |
exit := make(chan bool) | |
go func() { | |
for { | |
select { | |
case v := <-c: | |
rw.WriteString(v + "\n") | |
rw.Flush() | |
case <-exit: | |
con.Close() | |
return | |
} | |
} | |
}() | |
for { | |
bline, _, er := rw.ReadLine() | |
if er != nil { | |
con.Close() | |
return | |
} | |
line := string(bline) | |
switch line { | |
case "exit": | |
exit <- true | |
return | |
default: | |
broadcast <- line | |
} | |
} | |
} | |
func main() { | |
broadcast := make(chan string) | |
ln, _ := net.Listen("tcp", ":3457") | |
clients := []chan string{} | |
go func() { | |
for { | |
msg := <-broadcast | |
for _, c := range clients { | |
c <- msg | |
} | |
} | |
}() | |
for { | |
con, _ := ln.Accept() | |
c := make(chan string) | |
clients = append(clients, c) | |
go echoLoop(c, broadcast, con) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment