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) } } }
3. Bind the address and port
main ( ) () { http.Handle(websocket.(handler.)) err := http.ListenAndServe(nil) err != nil { fmt.Println(err) } }
2. Writing VUE client
<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>
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!