An example of golang vue using websocket

藏色散人
Release: 2021-05-19 14:05:10
forward
2065 people have browsed it

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)
}
   }
}
Copy after login

3. Bind the address and port

main

(
)

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

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>
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template