誰能幫忙解釋一下下面的程式碼片段的意思嗎?
var partner = make(chan io.ReadWriteCloser) func match(c io.ReadWriteCloser) { fmt.Fprintln(c, "Waiting for a partner...") select { case partner <- c: // handled by the other goroutine case p := <-partner: chat(p, c) } }
完整版:
package main import ( "fmt" "golang.org/x/net/websocket" "html/template" "io" "log" "net/http" ) const listenAddr = "localhost:4000" type socket struct { conn *websocket.Conn done chan bool } func (s socket) Read(b []byte) (int, error) { return s.conn.Read(b) } func (s socket) Write(b []byte) (int, error) { return s.conn.Write(b) } func (s socket) Close() error { s.done <- true return nil } var rootTemplate = template.Must(template.New("root").Parse(`Websocket Chat - Golang <script> var input, output, websocket; function showMessage(msg) { var p = document.createElement("p"); p.innerHTML = msg; output.appendChild(p); } function onMessage(e) { showMessage(e.data); } function onClose() { showMessage("Connection closed."); } function onKeyUp(e) { if (e.keyCode === 13) { sendMessage(); } } function sendMessage() { var msg = input.value; input.value = ""; websocket.send(msg + "\n"); showMessage(msg); } function init() { input = document.getElementById("input"); input.addEventListener("keyup", onKeyUp, false); output = document.getElementById("output"); websocket = new WebSocket("ws://{{.}}/socket"); websocket.onmessage = onMessage; websocket.onclose = onClose; } window.addEventListener("load", init); </script> Say: `)) func rootHandler(w http.ResponseWriter, r *http.Request) { rootTemplate.Execute(w, listenAddr) } func socketHandler(conn *websocket.Conn) { s := socket{conn: conn, done: make(chan bool)} go match(s) <-s.done } var partner = make(chan io.ReadWriteCloser) func match(c io.ReadWriteCloser) { fmt.Fprintln(c, "Waiting for a partner...") select { case partner <- c: // handled by the other goroutine case p := <-partner: chat(p, c) } } func chat(a, b io.ReadWriteCloser) { fmt.Fprintln(a, "Found one! Say hi.") fmt.Fprintln(b, "Found one! Say hi.") errc := make(chan error, 1) go cp(a, b, errc) go cp(b, a, errc) if err := <-errc; err != nil { log.Println(err) } a.Close() b.Close() go io.Copy(b, a) io.Copy(a, b) } func cp(w io.Writer, r io.Reader, errc chan<- error) { _, err := io.Copy(w, r) errc <- err } func main() { http.HandleFunc("/", rootHandler) http.Handle("/socket", websocket.Handler(socketHandler)) err := http.ListenAndServe(listenAddr, nil) if err != nil { log.Fatal(err) } }
不太明白為什麼當第二個加入者加入聊天頻道時可以執行這個聊天功能。
看起來 HTTP 處理程序建立了一個 Web 套接字並開始等待另一方連線。這是因為當處理HTTP請求時,處理程序呼叫match
,這將在select
上阻塞,因為partner
通道既不可讀也不可寫入。沒有 goroutine 監聽它,或發送給它。
當第二個請求到來時,match
會再次從另一個 goroutine 中呼叫。現在有兩個 goroutine,並且它們可以匹配。其中一個 goroutine 可以發送到 partner
通道,另一個 goroutine 接收它。傳輸的物件是讀寫器,然後用於兩個夥伴之間的通訊。
以上是Golang websocket的詳細內容。更多資訊請關注PHP中文網其他相關文章!