备注: Go 团队决定在 Go 1 版本中将 websocket 包从标准库移到 code.google.com/p/gowebsocket 子库中。预计在不久的将来也会发生巨大的改变。

    导入 websocket 包将变成这样:

    1. import websocket code.google.com/p/go/websocket

    websocket 协议与 http 协议相比,它是基于客户端与服务器端会话的持久链接,除此之外,功能几乎和 http 相同。在示例 15.24 中,是一个典型的 websocket 服务,启动它,然后监听一个来自 websocket 客户端的输入。示例 15.25 是一个客户端代码,它会在 5 秒后终止。当一个客户端与服务器端连接后,服务器端后打印: new connection;当客户端停止的时候,服务器端会打印: EOF => closing connection 。

    译者注: 现在这个包已经被放在了 golang.org/x/net/websocket 中,要想使用它需要在命令行执行: go get golang.org/x/net/websocket

    代码 15.24—websocket_server.go:

    1. // websocket_server.go
    2. package main
    3. import (
    4. "fmt"
    5. "net/http"
    6. "code.google.com/p/go.net/websocket"
    7. )
    8. func server(ws *websocket.Conn) {
    9. fmt.Printf("new connection\n")
    10. buf := make([]byte, 100)
    11. for {
    12. if _, err := ws.Read(buf); err != nil {
    13. fmt.Printf("%s", err.Error())
    14. break
    15. }
    16. }
    17. fmt.Printf(" => closing connection\n")
    18. ws.Close()
    19. }
    20. func main() {
    21. http.Handle("/websocket", websocket.Handler(server))
    22. err := http.ListenAndServe(":12345", nil)
    23. if err != nil {
    24. panic("ListenAndServe: " + err.Error())
    25. }
    26. }

    代码 15.25—websocket_client.go:

    1. // websocket_client.go
    2. package main
    3. import (
    4. "fmt"
    5. "time"
    6. "code.google.com/p/go.net/websocket"
    7. )
    8. func main() {
    9. ws, err := websocket.Dial("ws://localhost:12345/websocket", "",
    10. "http://localhost/")
    11. if err != nil {
    12. panic("Dial: " + err.Error())
    13. }
    14. go readFromServer(ws)
    15. time.Sleep(5e9)
    16. ws.Close()
    17. }
    18. func readFromServer(ws *websocket.Conn) {
    19. buf := make([]byte, 1000)
    20. for {
    21. if _, err := ws.Read(buf); err != nil {
    22. fmt.Printf("%s\n", err.Error())
    23. break
    24. }
    25. }
    26. }