golang--gin+webSocket

golang--gin+webSocket,第1张

安装
go get github.com/gorilla/websocket
import (
	"fmt"
	"github.com/gorilla/websocket"
)

var Wss = new(webSocketServer)

func init() {
	Wss.Msg = make(chan []byte)
}

type webSocketServer struct {
	Ws  *websocket.Conn
	Msg chan []byte//将要发给前端的数据放入管道就会触发发送动作
}
//发数据
func (wss *webSocketServer) Writer() {
	for message := range wss.Msg {
		fmt.Println("wss=>", message)
		wss.Ws.WriteMessage(websocket.TextMessage, message)
	}
}

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"robot-pcshare/service/system"
)

var upGrader = &websocket.Upgrader{
	ReadBufferSize:  512,
	WriteBufferSize: 512,
	CheckOrigin:     func(r *http.Request) bool { return true },
}

//webSocket请求什么什么
func Ping(c *gin.Context) {
	//升级get请求为websocket协议
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	defer ws.Close()
	system.Wss.Ws = ws
	system.Wss.Writer()
}
路由注册
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func InitRouter() {
	var Router = gin.Default()
	Router.Use(middleware.Cors())
	Router.GET("/ws", controller.Ping)
	if err := http.ListenAndServe("0.0.0.0:8080", Router); err != nil {
		fmt.Println("err:", err)
	}
}

vue前端
<script>
  export default {
    name: "show",
    data() {
      return {
        webSockLink: "ws://127.0.0.1:8080/ws",
        msg: "",
      }
    },
    methods: {
      webSocketOnmessage(e) {
        let data = JSON.parse(e.data)
        console.log("收到消息:", JSON.parse(e.data))
        console.log("wss=>", data)
      },
      initWebSocket() {
        this.websock = new WebSocket(this.webSockLink)
        this.websock.onopen = this.webSocketOnopen
        this.websock.onerror = this.webSocketOnerror
        this.websock.onmessage = this.webSocketOnmessage
        this.websock.onclose = this.webSocketClose
      },
      webSocketOnopen() {
        console.log('WebSocket连接成功')
      },
      webSocketOnerror(e) {
        console.log('WebSocket连接发生错误')
      },
      webSocketClose(e) {
        console.log('关闭WebSocket连接')
      }
    },
    mounted() {
      this.initWebSocket()
    },
    destroyed() {
      this.webSocketClose()
    },
  }
</script>

案例1

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/994328.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存