diff --git a/examples/echo/README.md b/examples/echo/README.md index 6bb404f..14b5b09 100644 --- a/examples/echo/README.md +++ b/examples/echo/README.md @@ -2,8 +2,8 @@ This example shows a simple client and server. -The server echoes messages sent to it. The client sends a message every five -seconds and prints all messages received. +The server echoes messages sent to it. The client sends a message every second +and prints all messages received. To run the example, start the server: @@ -13,3 +13,7 @@ Next, start the client: $ go run client.go +The server includes a simple web client. To use the client, open +http://127.0.0.1:8080 in the browser. Click "Open" to open a connection to the +server, "Send" to send a message to the server and "Close" to close the +connection. diff --git a/examples/echo/client.go b/examples/echo/client.go index af6fa99..45a0231 100644 --- a/examples/echo/client.go +++ b/examples/echo/client.go @@ -15,13 +15,13 @@ import ( "github.com/gorilla/websocket" ) -var addr = flag.String("addr", "localhost:8081", "http service address") +var addr = flag.String("addr", "localhost:8080", "http service address") func main() { flag.Parse() log.SetFlags(0) - u := url.URL{Scheme: "ws", Host: *addr, Path: "/"} + u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) @@ -42,7 +42,7 @@ func main() { } }() - ticker := time.NewTicker(5 * time.Second) + ticker := time.NewTicker(time.Second) defer ticker.Stop() for t := range ticker.C { diff --git a/examples/echo/server.go b/examples/echo/server.go index 8923690..53d21f6 100644 --- a/examples/echo/server.go +++ b/examples/echo/server.go @@ -8,21 +8,18 @@ package main import ( "flag" + "html/template" "log" "net/http" "github.com/gorilla/websocket" ) -var addr = flag.String("addr", "localhost:8081", "http service address") +var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{} // use default options func echo(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/" { - http.Error(w, "Not found", 404) - return - } c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) @@ -44,13 +41,84 @@ func echo(w http.ResponseWriter, r *http.Request) { } } +func home(w http.ResponseWriter, r *http.Request) { + homeTemplate.Execute(w, "ws://"+r.Host+"/echo") +} + func main() { flag.Parse() log.SetFlags(0) - - http.HandleFunc("/", echo) - err := http.ListenAndServe(*addr, nil) - if err != nil { - log.Fatal("ListenAndServe: ", err) - } + http.HandleFunc("/echo", echo) + http.HandleFunc("/", home) + log.Fatal(http.ListenAndServe(*addr, nil)) } + +var homeTemplate = template.Must(template.New("").Parse(` + + + + + + +
+ + +

+ +

+
+ + +`))