Last active
August 29, 2015 14:16
-
-
Save ericchiang/45c8e678cab4e5c947d9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"log" | |
"net/http" | |
"strconv" | |
"time" | |
"golang.org/x/net/websocket" | |
) | |
type Input struct { | |
Num string | |
} | |
type Output struct { | |
Num int | |
Error string | |
} | |
func main() { | |
// a websocket handler that reads in a number, attempts to parse it | |
// with Atoi(), then responds. | |
wsh := func(ws *websocket.Conn) { | |
for { | |
var input Input | |
if err := websocket.JSON.Receive(ws, &input); err != nil { | |
log.Println(err) | |
return | |
} | |
num, err := strconv.Atoi(input.Num) | |
msg := "" | |
if err != nil { | |
msg = err.Error() | |
} | |
if err := websocket.JSON.Send(ws, &Output{num, msg}); err != nil { | |
log.Println(err) | |
return | |
} | |
} | |
} | |
go func() { | |
log.Fatal(http.ListenAndServe(":7070", websocket.Handler(wsh))) | |
}() | |
// give the server a chance to start up | |
time.Sleep(time.Second) | |
// make a request to the server | |
origin := "http://localhost/" | |
url := "ws://localhost:7070/" | |
ws, err := websocket.Dial(url, "", origin) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// send a bunch of numbers over the websocket in JSON form | |
vals := []string{"7", "8", "foo"} | |
for _, n := range vals { | |
if err := websocket.JSON.Send(ws, &Input{n}); err != nil { | |
log.Fatal(err) | |
} | |
} | |
// recieve the response from the websocket one at a time | |
for range vals { | |
var output Output | |
if err := websocket.JSON.Receive(ws, &output); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("'%d' '%s'\n", output.Num, output.Error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment