Skip to content

Instantly share code, notes, and snippets.

@lcezermf
Forked from cryptix/chat.go
Created April 8, 2016 00:56
Show Gist options
  • Save lcezermf/5c1ce39f560ead8640c3e01ad68254bb to your computer and use it in GitHub Desktop.
Save lcezermf/5c1ce39f560ead8640c3e01ad68254bb 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