Преглед на файлове

Add web client to echo example

Gary Burd преди 10 години
родител
ревизия
c93e5540b8
променени са 3 файла, в които са добавени 88 реда и са изтрити 16 реда
  1. 6 2
      examples/echo/README.md
  2. 3 3
      examples/echo/client.go
  3. 79 11
      examples/echo/server.go

+ 6 - 2
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.

+ 3 - 3
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 {

+ 79 - 11
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(`
+<!DOCTYPE html>
+<head>
+<meta charset="utf-8">
+<script>  
+window.addEventListener("load", function(evt) {
+
+    var output = document.getElementById("output");
+    var input = document.getElementById("input");
+    var ws;
+
+    var print = function(message) {
+        var p = document.createElement("p");
+        p.innerHTML = message;
+        output.appendChild(p);
+    };
+
+    document.getElementById("open").onclick = function(evt) {
+        if (ws) {
+            return false;
+        }
+        ws = new WebSocket("{{.}}");
+        ws.onopen = function(evt) {
+            print("OPEN");
+        }
+        ws.onclose = function(evt) {
+            print("CLOSE");
+            ws = null;
+        }
+        ws.onmessage = function(evt) {
+            print("RESPONSE: " + evt.data);
+        }
+        ws.onerror = function(evt) {
+            print("ERROR: " + evt.data);
+        }
+        return false;
+    };
+
+    document.getElementById("send").onclick = function(evt) {
+        if (!ws) {
+            return false;
+        }
+        print("SEND: " + input.value);
+        ws.send(input.value);
+        return false;
+    };
+
+    document.getElementById("close").onclick = function(evt) {
+        if (!ws) {
+            return false;
+        }
+        ws.close();
+        return false;
+    };
+
+});
+</script>
+</head>
+<body>
+<form>
+<button id="open">Open</button>
+<button id="close">Close</button>
+<p><input id="input" type="text" value="Hello world!">
+<button id="send">Send</button>
+</form>
+<div id="output"></div>
+</body>
+</html>
+`))