cd go/src && mkdir -p golang.org/x
git clone https://github.com/golang/net
git clone https://github.com/golang/crypto
go get golang.org/x/net/websocket
package main
import(
"fmt"
"log"
"html/template"
"net/http"
"golang.org/x/net/websocket"
)
func web(w http.ResponseWriter,r *http.Request){
fmt.Println(r.Method)
if r.Method == "GET" {
t,_ := template.ParseFiles("websocket.html")
t.Execute(w,nil)
}
}
func Echo(ws *websocket.Conn){
var err error
for {
var reply string
err = websocket.Message.Receive(ws,&reply)
if err != nil {
fmt.Println("can not receive")
break
}
fmt.Println("received back from client:" + reply)
msg := "received " + reply
fmt.Println("send to client:" + msg)
err = websocket.Message.Send(ws,msg);
if err != nil {
fmt.Println("can not send")
break
}
}
}
func main(){
http.Handle("/websocket",websocket.Handler(Echo))
http.HandleFunc("/web",web)
err := http.ListenAndServe("0.0.0.0:8888",nil)
if err != nil {
log.Fatal("listenandserve:",err)
}
}
<!doctype html>
<html>
<head>
<title>go的websocket使用</title>
</head>
<body>
<script>
var sock = null;
var sockUrl = "ws://192.168.186.129:8888/websocket";
window.onload = function() {
console.log("onload")
sock = new WebSocket(sockUrl)
sock.onopen = function(){
console.log("connect to" + sockUrl)
}
sock.onclose = function(e){
console.log("connect closed")
}
sock.onmessage = function(e) {
console.log("message receied" + e.data)
alert("message receied:" + e.data)
}
}
function send(){
var msg = document.getElementById('message').value;
sock.send(msg)
}
</script>
<input type="text" id ="message" value="test websocket"/>
<button onclick="send()">发送</button>
</body>
</html>