1. 程式人生 > 實用技巧 >go websocket

go websocket

第一個go websocket程式,使用github.com/gorilla/websocket框架

命令匯入:go get github.com/gorilla/websocket

具體程式碼幾乎都是拷貝網友的,東拼西湊的,先跑起來,具體再慢慢研究

package main
import (
"fmt"
"github.com/gorilla/websocket"
"net/http"
_ "net/http"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool{
return true
},
}

func main() {
http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Print("upgrade:", err)
return
}
for {
mt, message, err := c.ReadMessage()
if err != nil {
fmt.Println("read:", err)
break
}
fmt.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
fmt.Println("write:", err)
break
}
}
})

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html") //自己建立個html
})

http.ListenAndServe(":8011", nil)
}