Skip to content

Instantly share code, notes, and snippets.

@megakorre
Created January 29, 2013 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save megakorre/4668073 to your computer and use it in GitHub Desktop.
Save megakorre/4668073 to your computer and use it in GitHub Desktop.
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