2021-04-26 10:42:12 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-04-27 10:36:08 +00:00
|
|
|
"encoding/json"
|
|
|
|
"log"
|
2021-04-26 10:42:12 +00:00
|
|
|
"net/http"
|
2021-04-27 10:36:08 +00:00
|
|
|
"time"
|
2021-04-26 10:42:12 +00:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2021-04-27 10:36:08 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2021-04-26 10:42:12 +00:00
|
|
|
)
|
|
|
|
|
2021-04-27 10:36:08 +00:00
|
|
|
var upGrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
|
|
return true
|
|
|
|
},
|
2021-04-26 10:42:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
eg := gin.Default()
|
|
|
|
eg.Use(Cors())
|
2021-04-27 10:36:08 +00:00
|
|
|
|
|
|
|
eg.GET("start", func(c *gin.Context) {
|
2021-04-26 10:42:12 +00:00
|
|
|
c.JSON(0, gin.H{
|
2021-04-27 10:36:08 +00:00
|
|
|
"task": "ok",
|
2021-04-26 10:42:12 +00:00
|
|
|
})
|
|
|
|
})
|
2021-04-27 10:36:08 +00:00
|
|
|
|
|
|
|
eg.GET("task", func(c *gin.Context) {
|
|
|
|
//升级get请求为webSocket协议
|
|
|
|
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
mt, message, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
c.Error(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
|
|
|
//读取ws中的数据
|
|
|
|
|
|
|
|
log.Println(
|
|
|
|
"123",
|
|
|
|
)
|
|
|
|
msg := gin.H{
|
|
|
|
"content": string(message),
|
|
|
|
}
|
|
|
|
data, err := json.Marshal(msg)
|
|
|
|
if err != nil {
|
|
|
|
log.Println(err)
|
|
|
|
}
|
|
|
|
//写入ws数据
|
|
|
|
err = ws.WriteMessage(mt, data)
|
|
|
|
if err != nil {
|
|
|
|
c.Error(err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
time.Sleep(time.Second * 10)
|
|
|
|
}
|
|
|
|
|
|
|
|
})
|
2021-04-26 10:42:12 +00:00
|
|
|
eg.Run(":12203")
|
|
|
|
}
|