最近一直在尝试着VUE中使用websocket连接,尝试了很多次终于满足我的要求
<template>
<mu-row>
<mu-button @click="click">test</mu-button>
<mu-button @click="click1">test1</mu-button>
</mu-row>
</template>
<script>
export default {
data(){
return {
}
},
created(){
this.init()
},
methods: {
init(){
this.GLOBAL.web = new WebSocket("ws://192.168.56.103:8081/ws")
},
click() {
this.GLOBAL.web.onmessage = function(evt){console.log("*********");console.log(evt.data);}
this.GLOBAL.web.send("dsfsd");
},
click1(){
this.GLOBAL.web.onmessage = function(evt){console.log("###############");console.log(evt.data);}
this.GLOBAL.web.send("dsfsdkkk");
}
},
destroyed (){this.GLOBAL.web.close()}
}
</script>
我觉得,这样websocket只连接一次,后可以一直交互, 只是这样有一个问题,并发访问会有问题吗?
也许 onmessage 不用每次重写,不用每次click 重写onmessage.
后端测试代码如下:
var upgrader = websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true }}
func Serverws(w http.ResponseWriter, r *http.Request) {
fmt.Println("IN request")
con, err := upgrader.Upgrade(w, r, nil)
defer con.Close()
fmt.Println("Connect")
if err != nil {
log.Println(err)
return
}
fmt.Println("start get")
con.SetReadLimit(1024)
for {
mtype, data, err := con.ReadMessage()
if err != nil {
fmt.Println(err)
}
fmt.Printf("type: %d data:%s\n", mtype, string(data))
con.WriteMessage(mtype, data)
}
}
func main() {
http.HandleFunc("/ws", Serverws)
http.ListenAndServe(":8081", nil)
}