Added Point, talking with gob

This commit is contained in:
Stephen McQuay 2015-02-04 21:24:45 -08:00
parent 72ba52557f
commit 2a0828f3c3
3 changed files with 42 additions and 11 deletions

View File

@ -1,8 +1,9 @@
package main package main
import ( import (
"bufio" "encoding/gob"
"fmt" "fmt"
"log"
"net" "net"
"os" "os"
@ -17,25 +18,25 @@ func main() {
} }
point := robo.Point{}
for { for {
var err error
conn, err := ln.Accept() conn, err := ln.Accept()
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err) fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1) os.Exit(1)
} }
s := bufio.NewScanner(conn) dec := gob.NewDecoder(conn)
for s.Scan() { for {
txt := s.Text() err = dec.Decode(&point)
fmt.Printf("sending: %s\n", txt)
_, err := conn.Write([]byte(txt + "\n"))
if err != nil { if err != nil {
break break
} }
log.Printf("%+v", point)
} }
if err := s.Err(); err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err) fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
} }
fmt.Printf("disconnect: %+v\n", conn) fmt.Printf("disconnect: %+v\n", conn)

View File

@ -2,9 +2,12 @@ package main
import ( import (
"bufio" "bufio"
"encoding/gob"
"fmt" "fmt"
"net" "net"
"os" "os"
"strconv"
"strings"
"mcquay.me/robo" "mcquay.me/robo"
) )
@ -17,21 +20,44 @@ func main() {
os.Exit(1) os.Exit(1)
} }
var err error
var x, y float64
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", os.Args[1], robo.Port)) conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", os.Args[1], robo.Port))
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err) fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1) os.Exit(1)
} }
enc := gob.NewEncoder(conn)
s := bufio.NewScanner(os.Stdin) s := bufio.NewScanner(os.Stdin)
point := robo.Point{}
for s.Scan() { for s.Scan() {
txt := s.Text() txt := s.Text()
fmt.Printf("sending: %s\n", txt) parts := strings.Split(txt, ",")
_, err := conn.Write([]byte(txt + "\n")) if len(parts) != 2 {
err = fmt.Errorf("bad parse from stdin: %q", txt)
break
}
x, err = strconv.ParseFloat(parts[0], 32)
if err != nil { if err != nil {
break 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 { if err := s.Err(); err != nil {

View File

@ -1,3 +1,7 @@
package robo package robo
const Port = 1337 const Port = 1337
type Point struct {
X, Y float64
}