From 2a0828f3c34e181848a8f31546a8a6a5c3ca2dc8 Mon Sep 17 00:00:00 2001 From: stephen mcquay Date: Wed, 4 Feb 2015 21:24:45 -0800 Subject: [PATCH] Added Point, talking with gob --- cmd/rrecv/main.go | 17 +++++++++-------- cmd/rsend/main.go | 32 +++++++++++++++++++++++++++++--- robo.go | 4 ++++ 3 files changed, 42 insertions(+), 11 deletions(-) diff --git a/cmd/rrecv/main.go b/cmd/rrecv/main.go index bda8fe2..e437a17 100644 --- a/cmd/rrecv/main.go +++ b/cmd/rrecv/main.go @@ -1,8 +1,9 @@ package main import ( - "bufio" + "encoding/gob" "fmt" + "log" "net" "os" @@ -17,25 +18,25 @@ func main() { } + point := robo.Point{} for { + var err error conn, err := ln.Accept() if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) } - s := bufio.NewScanner(conn) - for s.Scan() { - txt := s.Text() - fmt.Printf("sending: %s\n", txt) - _, err := conn.Write([]byte(txt + "\n")) + dec := gob.NewDecoder(conn) + for { + err = dec.Decode(&point) if err != nil { break } + log.Printf("%+v", point) } - if err := s.Err(); err != nil { + if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) - os.Exit(1) } fmt.Printf("disconnect: %+v\n", conn) diff --git a/cmd/rsend/main.go b/cmd/rsend/main.go index 225d905..71e2596 100644 --- a/cmd/rsend/main.go +++ b/cmd/rsend/main.go @@ -2,9 +2,12 @@ package main import ( "bufio" + "encoding/gob" "fmt" "net" "os" + "strconv" + "strings" "mcquay.me/robo" ) @@ -17,21 +20,44 @@ func main() { os.Exit(1) } + var err error + var x, y float64 conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", os.Args[1], robo.Port)) if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) os.Exit(1) - } + enc := gob.NewEncoder(conn) + s := bufio.NewScanner(os.Stdin) + point := robo.Point{} for s.Scan() { txt := s.Text() - fmt.Printf("sending: %s\n", txt) - _, err := conn.Write([]byte(txt + "\n")) + parts := strings.Split(txt, ",") + if len(parts) != 2 { + err = fmt.Errorf("bad parse from stdin: %q", txt) + break + } + x, err = strconv.ParseFloat(parts[0], 32) if err != nil { break } + y, err = strconv.ParseFloat(parts[1], 32) + if err != nil { + break + } + point.X, point.Y = x, y + + fmt.Printf("sending: %s\n", txt) + err = enc.Encode(&point) + if err != nil { + break + } + } + if err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) } if err := s.Err(); err != nil { diff --git a/robo.go b/robo.go index 058e8f3..10a43c5 100644 --- a/robo.go +++ b/robo.go @@ -1,3 +1,7 @@ package robo const Port = 1337 + +type Point struct { + X, Y float64 +}