前言
Go通过Websocket协议(ws://)建立服务端和客户端
下载依赖
1
| go get github.com/gorilla/websocket
|
服务端
<port>:监听端口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package main
import ( "fmt" "github.com/gorilla/websocket" "net/http" )
var UP = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, }
func handler(w http.ResponseWriter, r *http.Request) { conn, _ := UP.Upgrade(w, r, nil) for { m, p, e := conn.ReadMessage() if e != nil { fmt.Println("连接已断开") break } fmt.Println(m, string(p)) if string(p) == "ping" { conn.WriteMessage(websocket.TextMessage, []byte("pong")) } } }
func main() { http.HandleFunc("/", handler) fmt.Println("服务端已启动") http.ListenAndServe("0.0.0.0:<port>", nil) }
|
客户端
<ip>:服务端IP地址
<port>:服务端端口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| package main
import ( "fmt" "github.com/gorilla/websocket" "os" "runtime" "time" )
func main() { start: dl := websocket.Dialer{} conn, _, e := dl.Dial("ws://<ip>:<port>", nil) if e != nil { time.Sleep(2 * time.Second) goto start } defer conn.Close() for { conn.WriteMessage(websocket.TextMessage, []byte("ping")) m, p, e := conn.ReadMessage() if e != nil { time.Sleep(2 * time.Second) goto start } fmt.Println(m, string(p)) } }
|
发送数据
websocket.TextMessage:传输的数据类型为字符串消息
<text>:发送的文本内容
1
| conn.WriteMessage(websocket.TextMessage, []byte("<text>"))
|
接收数据
m:传输的数据类型
p:具体消息内容
e:错误
1
| m, p, e := conn.ReadMessage()
|
完成
参考文献
哔哩哔哩——go圈里最会写js的奇淼
稀土掘金——中亿丰数字科技集团有限公司