Skip to content

Instantly share code, notes, and snippets.

@cryptix
Created February 2, 2013 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cryptix/4698877 to your computer and use it in GitHub Desktop.
Save cryptix/4698877 to your computer and use it in GitHub Desktop.
simple chat example in go. uses channels to match partners and goroutines for concurency
package main
import (
"fmt"
"io"
"log"
"net"
)
const listenAddr = "localhost:4000"
var partner = make(chan io.ReadWriteCloser)
func match(c io.ReadWriteCloser) {
fmt.Fprint(c, "Waiting for a partner....")
select {
case partner <- c:
// now handled by the other goroutine
case p := <-partner:
chat(p, c)
}
}
func chat(a, b io.ReadWriteCloser) {
fmt.Fprintln(a, "Found one! Say Hi!")
fmt.Fprintln(b, "Found one! Say Hi!")
go io.Copy(a, b)
io.Copy(b, a)
}
func main() {
l, err := net.Listen("tcp", listenAddr)
if err != nil {
log.Fatal(err)
}
for {
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go match(c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment