go websocket

weixin_33866037發表於2018-07-12

獲得相應包支援:go get golang.org/x/net/websocket

package main

import (
    "log"
    "net/http"
    "os"
    "golang.org/x/net/websocket"
)

func main() {
    log.Println(os.Args[0]) //第一個引數,顯示檔案路徑
    http.Handle("/", websocket.Handler(Echo))
    if err := http.ListenAndServe(":8088", nil); err != nil {
        log.Println(err)
    }
}

func Echo(ws *websocket.Conn) {
    for {
        var raply string
        if err := websocket.Message.Receive(ws, &raply); err != nil { //get infomation,write in adress
            log.Println("can't receive")
            break
        }
        msg := "Received:" + raply
        log.Println(msg)
        if err := websocket.Message.Send(ws, "come back infomation"); err != nil { //send infomation
            log.Println("can't send")
            break
        }
    }
}

解釋:
(1)http.Handle("/", websocket.Handler(Echo))
主函式中的handle函式,將路由和相關的方法聯絡起來,不過要經過轉化
(2)func Echo(ws *websocket.Conn)
這個函式中實現了邏輯的實行,for迴圈一直處理使用者請求
其中: websocket.Message.Receive(ws, &raply)實現了資料的接收,存入對應的記憶體地址。
websocket.Message.Send(ws, "come back infomation")傳送相應的資料,前臺可以接收這個資料。

以下是前臺模擬
192.168.149.1是我自己電腦的IP,根據自己的IP不同,提交的地址不一樣,在這裡改成自己的IP地址或者想要提交的伺服器地址即可

<html>
    <head>
        <title></title>
    </head>
    <body>
        <script>
        var sock=null
        var wxurl="ws://192.168.149.1:8088"
        window.onload=function(){
            sock= new WebSocket(wxurl)
            sock.onopen = function(){
                console.log("connect to "+wxurl)
            }
            sock.onmessage = function(e){
                console.log("message:"+e.data)
                alert(e.data)
                $("#cs").text(e.data)
            }
            sock.onclose = function(e){
                console.log("close:"+e.code)
            }
        }

        function send(){
            var msg = document.getElementById("ms").value
        sock.send(msg)
        }
        </script>
        <form>
            <input id="ms" type="text" value="hello word" >
           <label id="cs"></label>
        </form>
        <button onclick="send()" >push</button>
    </body>
</html>

相關文章