add chapter 15.11 (#688)

This commit is contained in:
marjune
2019-07-19 11:52:06 +08:00
committed by ᴊ. ᴄʜᴇɴ
parent 3dafa4ed22
commit 0aecb0d588
3 changed files with 138 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
// websocket_client.go
package main
import (
"fmt"
"time"
"code.google.com/p/go.net/websocket"
)
func main() {
ws, err := websocket.Dial("ws://localhost:12345/websocket", "",
"http://localhost/")
if err != nil {
panic("Dial: " + err.Error())
}
go readFromServer(ws)
time.Sleep(5e9)
ws.Close()
}
func readFromServer(ws *websocket.Conn) {
buf := make([]byte, 1000)
for {
if _, err := ws.Read(buf); err != nil {
fmt.Printf("%s\n", err.Error())
break
}
}
}

View File

@@ -0,0 +1,29 @@
// websocket_server.go
package main
import (
"fmt"
"net/http"
"code.google.com/p/go.net/websocket"
)
func server(ws *websocket.Conn) {
fmt.Printf("new connection\n")
buf := make([]byte, 100)
for {
if _, err := ws.Read(buf); err != nil {
fmt.Printf("%s", err.Error())
break
}
}
fmt.Printf(" => closing connection\n")
ws.Close()
}
func main() {
http.Handle("/websocket", websocket.Handler(server))
err := http.ListenAndServe(":12345", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}