package controllers
import (
"net/http"
"time"
"github.com/astaxie/beego"
"github.com/gorilla/websocket"
)
type TestController struct {
beego.Controller
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { // 跨域
return true
},
}
// @router /test/index [get]
func (this *TestController) Get() { //页面展示
this.TplName = "danmuDemo.html"
}
func (this *TestController) WsFunc() {
var (
conn *websocket.Conn
err error
data []byte
)
// 配置连接
if conn, err = upgrader.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil); err != nil {
goto ERR
}
// 启动协程
go func() {
for {
// 发送hello到应用端
if err = conn.WriteMessage(websocket.TextMessage, []byte("Hello")); err != nil {
return
}
// 心跳,1s发送一次
time.Sleep(1 * time.Second)
}
}()
for {
// 接收数据有问题
if _, data, err = conn.ReadMessage(); err != nil {
goto ERR
}
// 发送数据有问题
if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
goto ERR
}
}
ERR:
conn.Close()
}