直接使用官方子包能夠實現websocket協議,javascript
package main import ( "time" "log" "net/http" "golang.org/x/net/websocket" ) func main(){ http.HandleFunc("/",index) http.Handle("/websocket",websocket.Handler(instantMessage)) log.Println("start server") err:=http.ListenAndServe(":1234",nil) log.Println(err) } func index(res http.ResponseWriter,req *http.Request){ res.Write([]byte("hello world")) } func instantMessage(w *websocket.Conn) { var error error for { var reply string if error= websocket.Message.Receive(w,&reply);error!=nil{ log.Println("接受消息失敗",error) break } log.Println("客戶端:",reply) msg:="服務端:"+reply+time.Now().String() log.Println(msg) if error = websocket.Message.Send(w, msg); error != nil { log.Println("發送消息失敗") break } } }
客戶端代碼:html
<html> <head> <title>好好學習</title> </head> <body> <script type="text/javascript"> var sock = null; // var wsuri = "wss://127.0.0.1:8080"; //本地的地址 是能夠改變的哦 var wsuri = "ws://localhost:1234/websocket"; //本地的地址 是能夠改變的哦 window.onload = function() { //能夠看到客戶端JS,很容易的就經過WebSocket函數創建了一個與服務器的鏈接sock,當握手成功後,會觸發WebScoket對象的onopen事件,告訴客戶端鏈接已經成功創建。客戶端一共綁定了四個事件。 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); document.getElementById('receive').innerHTML=e.data; } //發生錯誤的時候觸發 sock.onerror=function (e) { console.log("發生錯誤時候觸發"+wsuri) } }; //若是sock被關閉掉了 這裏 也會報錯的啊 function send() { var msg = document.getElementById('message').value; sock.send(msg); }; </script> <h1>客戶端</h1> <form> <p>發送: </p> <textarea id="message" >我是陶士涵</textarea> <p>接收: </p> <textarea id="receive" ></textarea> </form> <button onclick="send();">給服務器發送消息</button> </body> </html>