You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
1.9 KiB
97 lines
1.9 KiB
4 years ago
|
package ws
|
||
4 years ago
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"github.com/gorilla/websocket"
|
||
|
"github.com/taoshihan1991/imaptool/models"
|
||
|
"log"
|
||
|
)
|
||
|
|
||
|
func NewKefuServer(c *gin.Context) {
|
||
|
kefuId, _ := c.Get("kefu_name")
|
||
|
kefuInfo := models.FindUser(kefuId.(string))
|
||
|
if kefuInfo.ID == 0 {
|
||
|
c.JSON(200, gin.H{
|
||
|
"code": 400,
|
||
|
"msg": "用户不存在",
|
||
|
})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
go kefuServerBackend()
|
||
|
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||
|
if err != nil {
|
||
|
log.Print("upgrade:", err)
|
||
|
return
|
||
|
}
|
||
4 years ago
|
//获取GET参数,创建WS
|
||
|
var kefu User
|
||
|
kefu.Id = kefuInfo.Name
|
||
|
kefu.Name = kefuInfo.Nickname
|
||
|
kefu.Avator = kefuInfo.Avator
|
||
|
kefu.Conn = conn
|
||
|
AddKefuToList(&kefu)
|
||
|
|
||
4 years ago
|
for {
|
||
|
//接受消息
|
||
|
var receive []byte
|
||
|
messageType, receive, err := conn.ReadMessage()
|
||
|
if err != nil {
|
||
|
log.Println(err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
message <- &Message{
|
||
|
conn: conn,
|
||
|
content: receive,
|
||
|
context: c,
|
||
|
messageType: messageType,
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
func AddKefuToList(kefu *User) {
|
||
|
var newKefuConns = []*User{kefu}
|
||
4 years ago
|
kefuConns := KefuList[kefu.Id]
|
||
4 years ago
|
if kefuConns != nil {
|
||
4 years ago
|
for _, kefu := range kefuConns {
|
||
|
msg := TypeMessage{
|
||
|
Type: "pong",
|
||
|
}
|
||
|
str, _ := json.Marshal(msg)
|
||
|
err := kefu.Conn.WriteMessage(websocket.TextMessage, str)
|
||
|
if err != nil {
|
||
|
newKefuConns = append(newKefuConns, kefu)
|
||
|
}
|
||
|
}
|
||
4 years ago
|
}
|
||
4 years ago
|
log.Println(newKefuConns)
|
||
4 years ago
|
KefuList[kefu.Id] = newKefuConns
|
||
4 years ago
|
}
|
||
|
|
||
|
//后端广播发送消息
|
||
|
func kefuServerBackend() {
|
||
|
for {
|
||
|
message := <-message
|
||
|
var typeMsg TypeMessage
|
||
|
json.Unmarshal(message.content, &typeMsg)
|
||
|
conn := message.conn
|
||
|
if typeMsg.Type == nil || typeMsg.Data == nil {
|
||
|
continue
|
||
|
}
|
||
|
msgType := typeMsg.Type.(string)
|
||
4 years ago
|
log.Println("客户端:", string(message.content))
|
||
4 years ago
|
|
||
|
switch msgType {
|
||
|
//心跳
|
||
|
case "ping":
|
||
|
msg := TypeMessage{
|
||
|
Type: "pong",
|
||
|
}
|
||
|
str, _ := json.Marshal(msg)
|
||
|
conn.WriteMessage(websocket.TextMessage, str)
|
||
|
}
|
||
|
|
||
|
}
|
||
|
}
|