时间:2021-10-07 10:59:34 | 栏目:Golang | 点击:次
Go 搭建一个简单 WebSocket 服务端代码例子 test.go, 如下:
package main import ( "fmt" "log" "net/http" "golang.org/x/net/websocket" ) func Echo(ws *websocket.Conn) { var err error for { var reply string if err = websocket.Message.Receive(ws, &reply); err != nil { fmt.Println("Can't receive") break } fmt.Println("Received back from client: " + reply) msg := "Received: " + reply fmt.Println("Sending to client: " + msg) if err = websocket.Message.Send(ws, msg); err != nil { fmt.Println("Can't send") break } } } func main() { http.Handle("/", websocket.Handler(Echo)) if err := http.ListenAndServe(":1234", nil); err != nil { log.Fatal("ListenAndServe:", err) } }
运行服务端:
go run test.go
在 Firefox 或 Chrome 控制台,可以用以下代码发起客户端的 WebSocket 连接:
var wsServer = 'ws://localhost:1234'; var websocket = new WebSocket(wsServer); websocket.onopen = function (evt) { console.log("Connected to WebSocket server."); }; websocket.onclose = function (evt) { console.log("Disconnected"); }; websocket.onmessage = function (evt) { console.log('Retrieved data from server: ' + evt.data); }; websocket.onerror = function (evt, e) { console.log('Error occured: ' + evt.data); };
执行以上代码,得到输出日志:Connected to WebSocket server,表示 WebSocket 连接建立成功。
使用如下代码可以发送数据,如:
websocket.send(2323)
并且马上得到服务端返回的内容,这里是原样返回。
服务端日志如下:
这就使用 Go 搭建了一个简单的 WebSocket 服务端。
总结