Skip to content

Instantly share code, notes, and snippets.

@porty
Last active August 29, 2015 14:05
Show Gist options
  • Save porty/d1ac53a0038ad12943f5 to your computer and use it in GitHub Desktop.
Save porty/d1ac53a0038ad12943f5 to your computer and use it in GitHub Desktop.
Emitter
package main
import (
"bufio"
"fmt"
"io"
"os"
"github.com/porty/emitter"
)
type chatData struct {
Who string
Message string
}
func server() {
a, err := emitter.NewAbsorber()
if err != nil {
panic(err)
}
for {
p, err := a.WaitForPacket()
if err != nil {
panic(err)
}
c := chatData{}
err = p.AsType(&c)
if err != nil {
panic(err)
}
fmt.Printf("%s says '%s'\n", c.Who, c.Message)
}
}
func client() {
e := emitter.NewEmitter()
c := chatData{}
bio := bufio.NewReader(os.Stdin)
fmt.Print("Who are you? ")
line, _, err := bio.ReadLine()
if err != nil {
panic(err)
}
c.Who = string(line)
for {
fmt.Print("> ")
line, _, err := bio.ReadLine()
if err != nil {
if err == io.EOF {
fmt.Println()
break
}
panic(err)
}
c.Message = string(line)
e.Emit("chat", c)
}
}
func showUsage() {
fmt.Println("Specify server or client")
os.Exit(1)
}
func main() {
if len(os.Args) != 2 {
showUsage()
}
if os.Args[1] == "server" {
server()
} else if os.Args[1] == "client" {
client()
} else {
showUsage()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment