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)
}

 

posted on 2020-07-23 16:02  3SU  阅读(359)  评论(0编辑  收藏  举报