加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang vue 使用 websocket 的例子

发布时间:2020-12-16 09:29:27 所属栏目:大数据 来源:网络整理
导读:一.?编写golang服务端 ?1.导入必要的websocket包,golang.org/x/net/websocket?或 github.com/golang/net/websocket ?2.编写消息处理函数,主要实现接收客户端发送的消息和向客户端发送消息 ? func Handle (conn *websocket. Conn ) { defer conn.Close() js

一.?编写golang服务端

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

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

?

func Handle(conn *websocket.Conn) {
defer conn.Close()
jsonHandler := websocket.JSON
userInfo := &UserInfo{}
res := &Response{
Code: 1,
Msg: "success",
}
go Push(conn)
for {
err := jsonHandler.Receive(conn,userInfo)
if err != nil {
fmt.Println(err)
break
}
jsonData,_ := json.Marshal(userInfo)
fmt.Println("receive data:",string(jsonData[:]))
err = jsonHandler.Send(conn,res)
if err != nil {
fmt.Println(err)
break
}
}
}

?3.绑定地址及端口


package main

import (
"fmt"
"golang.org/x/net/websocket"
"net/http"
"w3liu.com/websocket/handler"
)

func main() {
http.Handle("/ws",websocket.Handler(handler.Handle))
err := http.ListenAndServe(":88",nil)
if err != nil {
fmt.Println(err)
}
}

?

二、编写VUE客户端

??

< template >
< div >
{{ msg}}
</ div >
</ 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读