首頁  >  文章  >  後端開發  >  一個golang vue使用websocket 的例子

一個golang vue使用websocket 的例子

藏色散人
藏色散人轉載
2021-05-19 14:05:102000瀏覽

下面由golang教學專欄來介紹一個golang vue使用websocket 的範例 ,希望對需要的朋友有幫助!

一. 寫golang服務端

 1.導入必要的websocket包,golang.org/x/net/websocket 或github.com/golang/net/ websocket

 2.編寫訊息處理函數,主要實作接收客戶端傳送的訊息及傳送訊息 

(conn *websocket.) {
conn.Close()
   jsonHandler := websocket.JSON
   userInfo := &{}
   res := &{
      Code: Msg:  }
Push(conn)
{
      err := jsonHandler.Receive(connuserInfo)
err != nil {
         fmt.Println(err)
}
      jsonData_ := json.Marshal(userInfo)
      fmt.Println((jsonData[:]))
      err = jsonHandler.Send(connres)
err != nil {
         fmt.Println(err)
}
   }
}

 3.綁定位址及連接埠

main

(
)

() {
   http.Handle(websocket.(handler.))
   err := http.ListenAndServe(nil)
err != nil {
      fmt.Println(err)
   }
}

 二、寫VUE客戶端

<template>
<p>
{{msg}}
</p>
</template>
<script>
export default {
data () {
return {
websock: null,
msg: &#39;&#39;
}
},
methods: {
init: function () {
const wsurl = &#39;ws://127.0.0.1:88/ws&#39;
this.websock = new WebSocket(wsurl)
this.websock.onmessage = this.onmessage
this.websock.onopen = this.onopen
this.websock.onerror = this.onerror
this.websock.onclose = this.onclose
},
onopen: function () {
this.send(&#39;{"userid":1, "name":"zhang san", "age":"30"}&#39;)
},
send: function (data) {
for (var i = 0; i < 10; i++) {
this.websock.send(data)
}
},
onclose: function (e) {
console.log(&#39;ws close&#39;, e)
},
onmessage: function (e) {
let _this = this
console.log(e.data)
_this.msg = e.data
},
onerror: function () {
console.log(&#39;ws error&#39;)
this.init()
}
},
mounted: function () {
this.init()
},
watch: {
}
}
</script>

  完整原始碼存取:https://github.com/w3liu/websocket

 

#

以上是一個golang vue使用websocket 的例子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除