Golang如何使用websocket
下载websocket包
$ go get golang.org/x/net/websocket
如果下载失败,可能是被墙了。
package golang.org/x/net/websocket: unrecognized import path “golang.org/x/net/websocket” (https fetch: Get https://golang.org/x/net/websocket?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
可以尝试
$ go get -u github.com/golang/net/websocket
下载后记得将路径改成golang.org/x/net/websocket
$ cd $GOPATH
$ mkdir -p golang.org/x/net
$ cp github.com/golang/net/websocket/ golang.org/x/net/ -R
实例
服务端代码
server.go
package main
import (
"fmt"
"golang.org/x/net/websocket"
"html/template" //支持模板html
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
//websocket接受信息
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("receive failed:", err)
break
}
fmt.Println("reveived from client: " + reply)
msg := "received:" + reply
fmt.Println("send to client:" + msg)
//这里是发送消息
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("send failed:", err)
break
}
}
}
func web(w http.ResponseWriter, r *http.Request) {
//打印请求的方法
fmt.Println("method", r.Method)
if r.Method == "GET" { //如果请求方法为get显示login.html,并相应给前端
t, _ := template.ParseFiles("websocket.html")
t.Execute(w, nil)
} else {
//否则走打印输出post接受的参数username和password
fmt.Println(r.PostFormValue("username"))
fmt.Println(r.PostFormValue("password"))
}
}
func main() {
//接受websocket的路由地址
http.Handle("/websocket", websocket.Handler(Echo))
//html页面
http.HandleFunc("/web", web)
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
客户端代码
websocket.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>go测试socket</title>
</head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:1234/websocket";
window.onload = function() {
console.log("onload");
sock = new WebSocket(wsuri);
sock.onopen = function() {
console.log("connected to " + wsuri);
}
sock.onclose = function(e) {
console.log("connection closed (" + e.code + ")");
}
sock.onmessage = function(e) {
console.log("message received: " + e.data);
}
};
function send() {
var msg = document.getElementById('message').value;
sock.send(msg);
};
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>
Message: <input id="message" type="text" value="Hello, world!">
</p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
测试
启动服务端
$ ./server
启动浏览器
输入http://127.0.0.1:1234/web
网络通信内容如图所示,首先加载页面,接着使用HTTP建立websocket连接,后续通信直接使用websocket进行。
点击 页面中SendMessage按钮
server端输出:
method GET
reveived from client: Hello, world!
send to client:received:Hello, world!
浏览器输出:
参考
https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/08.2.md
https://github.com/ukai/go-websocket-sample/blob/master/websocket_echo_sample.go
上一篇: Golang 如何使用Redis服务
下一篇: golang搭建项目教程