Websockets

这个例子将展示如何使用Websockets。我们将建立一个简单的server,它发回我们发给它所有的内容。这里我们用go get来下载 gorilla/websocket :

$ go get github.com/gorilla/websocket

接下来,我们所有的应用都将使用这个库.

  1. // websockets.go
  2. package main
  3. import (
  4. "fmt"
  5. "net/http"
  6. "github.com/gorilla/websocket"
  7. )
  8. var upgrader = websocket.Upgrader{
  9. ReadBufferSize: 1024,
  10. WriteBufferSize: 1024,
  11. }
  12. func main() {
  13. http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
  14. conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity
  15. for {
  16. // Read message from browser
  17. msgType, msg, err := conn.ReadMessage()
  18. if err != nil {
  19. return
  20. }
  21. // Print the message to the console
  22. fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))
  23. // Write message back to browser
  24. if err = conn.WriteMessage(msgType, msg); err != nil {
  25. return
  26. }
  27. }
  28. })
  29. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  30. http.ServeFile(w, r, "websockets.html")
  31. })
  32. http.ListenAndServe(":8080", nil)
  33. }
  1. <!-- websockets.html -->
  2. <input id="input" type="text" />
  3. <button onclick="send()">Send</button>
  4. <pre id="output"></pre>
  5. <script>
  6. var input = document.getElementById("input");
  7. var output = document.getElementById("output");
  8. var socket = new WebSocket("ws://localhost:8080/echo");
  9. socket.onopen = function () {
  10. output.innerHTML += "Status: Connected\n";
  11. };
  12. socket.onmessage = function (e) {
  13. output.innerHTML += "Server: " + e.data + "\n";
  14. };
  15. function send() {
  16. socket.send(input.value);
  17. input.value = "";
  18. }
  19. </script>
  1. $ go run websockets.go
  2. [127.0.0.1]:53403 sent: Hello Go Web Examples, you're doing great!