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
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)

View File

@ -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 {

View File

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