【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)
}}
推荐阅读
- 【golang】leetcode中级-字母异位词分组&无重复字符的最长子串
- 彻底理解Golang Map
- kratos线上开源年会它来啦~
- 深入浅出 Golang 资源嵌入方案(go-bindata篇)
- 深入浅出 Golang 资源嵌入方案(前篇)
- golang 经典案例总结
- Go实战 | 基于有向无环图的并发执行流的实现
- Golang 数组和切片
- Go JSON编码与解码()
- golang map基础知识