Created
February 2, 2013 19:17
-
-
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
This file contains hidden or 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 ( | |
"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