-
-
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
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 ( | |
"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