首页 >后端开发 >Golang > 正文

一个golang vue使用websocket 的例子

转载2021-05-19 14:05:100593
下面由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: ''
}
},
methods: {
init: function () {
const wsurl = 'ws://127.0.0.1:88/ws'
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('{"userid":1, "name":"zhang san", "age":"30"}')
},
send: function (data) {
for (var i = 0; i < 10; i++) {
this.websock.send(data)
}
},
onclose: function (e) {
console.log('ws close', e)
},
onmessage: function (e) {
let _this = this
console.log(e.data)
_this.msg = e.data
},
onerror: function () {
console.log('ws error')
this.init()
}
},
mounted: function () {
this.init()
},
watch: {
}
}
</script>

完整源码访问:https://github.com/w3liu/websocket

以上就是一个golang vue使用websocket 的例子的详细内容,更多请关注php中文网其它相关文章!

php中文网最新课程二维码

声明:本文转载于:cnblogs,如有侵犯,请联系admin@php.cn删除

  • 相关标签:golang
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    推荐视频教程
  • Go语言教程手册Go语言教程手册
  • go语言基础与基本函数go语言基础与基本函数
  • 视频教程分类