golang websocket 示例

【golang websocket 示例】websocket 包:

golang.org/x/net/websocket

通过js websocket连接未出现跨域问题。
package mainimport ( "fmt" "golang.org/x/net/websocket" "net/http" ); func echoHandler(ws *websocket.Conn) { defer func() { if r := recover(); r!=nil{ fmt.Println(r) } }() msg := make([]byte,512) for{strLen,err := ws.Read(msg)fmt.Println(string(msg[:strLen-1])) fmt.Println(strLen)if err !=nil { panic(err) } }}func main(){ mux := http.NewServeMux() mux.Handle("/ws",websocket.Handler(echoHandler)) server := &http.Server{ Addr : ":9990", Handler: mux, IdleTimeout: 9999, } defer func(){ if r:= recover(); r!= nil { fmt.Println(r) _ = server.Close() } }() if err := server.ListenAndServe(); err != nil { panic(err) }}


    推荐阅读