咱們經過使用以下庫建立websocket服務javascript
go get golang.org/x/net/websocket
websocket服務端的代碼以下:html
package main; import ( "golang.org/x/net/websocket" "net/http" "log" "fmt" ) //使用golang.org/x/net/websocket //若是沒法下載,請到下面的地址去下載 //http://www.golangtc.com/download/package //http://gopm.io/ type Msg struct { From string; To string; Data string; } //處理簡單的字符串 func test(conn *websocket.Conn) { var err error; for { data := ""; //接收消息 err = websocket.Message.Receive(conn, &data); if err != nil { break; } fmt.Println("client send: " + data); msg := "hello " + data; //發送消息 err = websocket.Message.Send(conn, msg); if err != nil { break; } } } //處理JSON數據 func test2(conn *websocket.Conn) { var err error; for { var data Msg; //接收消息 err = websocket.JSON.Receive(conn, &data); if err != nil { break; } fmt.Println(data.From, data.To, data.Data); msg := Msg{ From: data.From, To: data.To, Data: "hello " + data.Data, }; //發送消息 err = websocket.JSON.Send(conn, msg); if err != nil { break; } } } func main() { //http.Handle("/", websocket.Handler(test)); http.Handle("/", websocket.Handler(test2)); err := http.ListenAndServe(":8080", nil); if err != nil { log.Fatal(err); } }
html客戶端代碼以下:java
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket</title> </head> <body> <form> <input type="text" id="msg"> <input type="submit" id="sendBtn" value="發送"> </form> <div id="result"></div> <script type="text/javascript"> var url = "ws://127.0.0.1:8080"; var ws = new WebSocket(url); //ws打開時 ws.onopen = function() { console.log("connect ..."); }; //ws鏈接關閉時 ws.onclose = function() { console.log("close"); }; //監聽服務器推送數據 ws.onmessage = function(ev) { var result = document.getElementById("result"); result.innerHTML = result.innerHTML + "<p>" + ev.data + "</p>"; }; document.getElementById("sendBtn").onclick = function() { var msg = document.getElementById("msg").value; if(msg.length == 0) { alert("不能爲空"); } //發送數據 ws.send(msg); return false; }; </script> </body> </html>
json格式:golang
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket</title> </head> <body> <form> <input type="text" id="msg"> <input type="submit" id="sendBtn" value="發送"> </form> <div id="result"></div> <script type="text/javascript"> var url = "ws://127.0.0.1:8080"; var ws = new WebSocket(url); //ws打開時 ws.onopen = function() { console.log("connect ..."); }; //ws鏈接關閉時 ws.onclose = function() { console.log("close"); }; //監聽服務器推送數據 ws.onmessage = function(ev) { var result = document.getElementById("result"); var data = eval("(" + ev.data + ")"); result.innerHTML = result.innerHTML + "<p>" + data.From + "發送" + data.To + ":" + data.Data + "</p>"; }; document.getElementById("sendBtn").onclick = function() { var msg = document.getElementById("msg").value; if(msg.length == 0) { alert("不能爲空"); } //發送數據 //注意這裏JOSN的拼接,key和value要用雙引號,不然go沒法解析 ws.send('{"From":"小張","To":"小王","Data":"' + msg + '"}'); return false; }; </script> </body> </html>