一个golang vue使用websocket 的例子


本文摘自php中文网,作者藏色散人,侵删。

下面由golang教程栏目给大家介绍一个golang vue使用websocket 的例子 ,希望对需要的朋友有所帮助!

一. 编写golang服务端

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

2.编写消息处理函数,主要实现接收客户端发送的消息和向客户端发送消息

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

(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.绑定地址及端口

1

2

3

4

5

6

7

8

9

10

11

12

main

 

(

)

 

() {

   http.Handle(websocket.(handler.))

   err := http.ListenAndServe(nil)

err != nil {

      fmt.Println(err)

   }

}

二、编写VUE客户端

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<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 的例子的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

golang环境的安装

关于go modules的理解和遇到的问题

go2设计草案介绍

手撸golang 行为型设计模式 模板方法模式

golang在日志中打印堆栈信息

golang 如何安装包

为什么选择 golang?彻底解决争论

值得推荐的五种自动化代码审查工具

手撸golang spring ioc/aop 之2

分布式任务 + 消息队列框架 go-queue

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...