Home >Backend Development >Golang >An example of golang vue using websocket

An example of golang vue using websocket

藏色散人
藏色散人forward
2021-05-19 14:05:102094browse

The following tutorial column from golang will introduce you to an example of using websocket in golang vue. I hope it will be helpful to friends in need!

1. Writing golang server

1. Import the necessary websocket package, golang.org/x/net/websocket or github.com/golang/net/ websocket

2. Write a message processing function, mainly to receive messages sent by the client and send messages to the client

(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. Bind the address and port

main

(
)

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

2. Writing VUE client

<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>

Full source code access: https://github.com/w3liu/websocket

The above is the detailed content of An example of golang vue using websocket. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete