vue与go后端的websocket连接

vue端:








 beego后端:

package routers

import (
	"monitorServer/controllers"
	"github.com/astaxie/beego"
)

func init() {
    beego.Router("/", &controllers.MainController{})
    beego.Router("/ws", &controllers.MyWebSocketController{})
}





package controllers

import (
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
	"log"
	"monitorServer/models"
	"time"
)

type MyWebSocketController struct {
	beego.Controller
}

// 配置 upgrader
var upgrader = websocket.Upgrader{}

func (c *MyWebSocketController) Get() {
	// 将初始GET请求升级到websocket
	ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		log.Fatal(err)
	}
	// 返回时关闭连接
	defer ws.Close()

	// 将新的客户端连接添加到字典中
	clients[ws] = true

	//不断的广播发送到页面上
	for {
		//目前存在问题 定时效果不好 需要在业务代码替换时改为beego toolbox中的定时器
		time.Sleep(time.Second * 3)
		msg := models.Message{Message: "这是向页面发送的数据 " + time.Now().Format("2006-01-02 15:04:05")}
		broadcast <- msg
	}
}






package controllers

import (
	"monitorServer/models"
	"log"
	"github.com/gorilla/websocket"
)

// 使用字典结构更容易追加和删除内容
var (
	clients   = make(map[*websocket.Conn]bool)  // 保存连接的客户端
	broadcast = make(chan models.Message)  // 消息广播通道
)

func init() {
	go handleMessages()
}

// 发送
func handleMessages() {
	for {
		msg := <-broadcast
		// 将其发送给当前连接的每个客户端
		if len(clients) != 0 {
			for client := range clients {
				err := client.WriteJSON(msg)
				if err != nil {
					log.Printf("client.WriteJSON error: %v", err)
					client.Close()
					delete(clients, client)
				}
			}
		}
	}
}





package models

type Message struct {
    Message string `json:"message"`
}

参考:

https://www.jianshu.com/p/5284d4336a7c

你可能感兴趣的:(其他)