268 lines
7.3 KiB
Go
268 lines
7.3 KiB
Go
package mtwmapi
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"git.rosy.net.cn/baseapi/utils"
|
||
"github.com/gazeboxu/mapstructure"
|
||
"github.com/go-redis/redis"
|
||
"github.com/gorilla/websocket"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
const (
|
||
MTIMPushUrl = "wss://wpush.meituan.com/websocket"
|
||
TestAppID = "589_WMOPEN"
|
||
TestToken = "wo589i4VsZHFH2fh4uVsr6Dtc3k6vG8Xu0vxpreBQFy6QAvg"
|
||
|
||
TestMTIMPushUrl = "wss://wpush.meituan.com/websocket/589_WMOPEN/wo589i4VsZHFH2fh4uVsr6Dtc3k6vG8Xu0vxpreBQFy6QAvg"
|
||
)
|
||
|
||
type ClientManager struct {
|
||
ClientIdMap map[string]*Client // 全部的连接
|
||
ClientIdMapLock sync.RWMutex // 读写锁
|
||
|
||
Connect chan *Client // 连接处理
|
||
DisConnect chan *Client // 断开连接处理
|
||
|
||
GroupLock sync.RWMutex
|
||
Groups map[string][]string
|
||
|
||
//SystemClientsLock sync.RWMutex
|
||
//SystemClients map[string][]string
|
||
Clients map[string]*Client // 保存连接
|
||
Accounts map[string][]string // 账号和连接关系,map的key是账号id即:AccountId,这里主要考虑到一个账号多个连接
|
||
mu *sync.Mutex
|
||
}
|
||
|
||
var Manager = NewClientManager()
|
||
|
||
func NewClientManager() (clientManager *ClientManager) {
|
||
clientManager = &ClientManager{
|
||
Accounts: make(map[string][]string),
|
||
ClientIdMap: make(map[string]*Client, 100),
|
||
Connect: make(chan *Client, 10000),
|
||
DisConnect: make(chan *Client, 10000),
|
||
mu: new(sync.Mutex),
|
||
}
|
||
|
||
return
|
||
}
|
||
|
||
var RegisterChan = make(chan *Client, 100)
|
||
|
||
type Client struct {
|
||
ID string // 连接ID
|
||
AccountId string // 账号id, 一个账号可能有多个连接
|
||
Socket *websocket.Conn // 连接
|
||
HeartbeatTime int64 // 前一次心跳时间
|
||
}
|
||
|
||
var rdb = redis.NewClient(&redis.Options{
|
||
//Addr: "www.jxc4.com:6379",
|
||
//Password: "",
|
||
Addr: "127.0.0.1:6379",
|
||
Password: "123456",
|
||
DB: 0,
|
||
})
|
||
|
||
//测试心跳
|
||
func TestHeartCheck(t *testing.T) {
|
||
//go func() {
|
||
// ticker := time.NewTicker(5 * time.Second)
|
||
// defer ticker.Stop()
|
||
// for {
|
||
// <-ticker.C
|
||
//发送心跳
|
||
conn, resp, err := websocket.DefaultDialer.Dial(TestMTIMPushUrl, nil)
|
||
fmt.Println(resp, err)
|
||
err1 := conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second))
|
||
for {
|
||
_, msg, err := conn.ReadMessage()
|
||
if err != nil {
|
||
break
|
||
}
|
||
fmt.Printf("%s receive: %s\n", conn.RemoteAddr(), string(msg))
|
||
}
|
||
fmt.Println(err1)
|
||
//}
|
||
//}()
|
||
}
|
||
|
||
func TestGetConnectionToken(t *testing.T) {
|
||
resp, err := api.GetConnectionToken()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
retVal := GetConnTokenResp{}
|
||
err = mapstructure.Decode(resp, &retVal)
|
||
fmt.Println(err)
|
||
fmt.Println(utils.Format4Output(retVal, false))
|
||
}
|
||
|
||
//解密测试
|
||
func TestAesCBCDecrypt(t *testing.T) {
|
||
secret := "a81eb3df418d83d6a1a4b7c572156d2f"
|
||
key := secret[:16]
|
||
str := "qodhoVd4IGtgPKrvYwq6QrzBecJZkeSUPYR88iGRUsCRFmCFxDHpUhqsbBztNXQx"
|
||
//str := "Vv+Y/K8vfS42W+P7xq26aIb6uoaG/nL0ZoMMXpitc5QQ3XJm3Roh10NuSoojYrG/3JZwbzgtYA+kBvodoY2eJV00f9MBY+kLkxToP+aSofsYva9tHbipvjVtexebc+eP7aQMtzbwU4BNNnuRG6e7TkXP+BLdtiGsyvHolGfky+p2fZgWes9R6JIxkuRCXW/yBhUo8F+wWCZ2YQl/szp5lHJ3cmneD6cwem36E0FBcvxZNB9an4pRkBrqi1p43V8QBLO719oXkQ+dqTqJMi1/xDSBrCDYN8QORnARP8+j1oDuqE34Kklcse4WL9rwTJ2sOmOu/O2h6Gx3ZaFaMaWRXBDYv8JpzTZjCbRrLSENlEHTof29BmvXTJ0QZ7qi6iAD"
|
||
data, err := Decrypt(str, []byte(key))
|
||
//data, err := DecryptAES(key, str)
|
||
fmt.Println(data)
|
||
fmt.Println(err)
|
||
}
|
||
|
||
var wsList []*websocket.Conn
|
||
|
||
func sendmsg() {
|
||
for _, conn := range wsList {
|
||
if err := conn.WriteMessage(websocket.TextMessage, []byte("~#HHHBBB#~")); err != nil {
|
||
fmt.Printf("%s", err) //"use of closed network connection"
|
||
}
|
||
}
|
||
}
|
||
func TestPut(t *testing.T) {
|
||
fmt.Println(wsList)
|
||
}
|
||
|
||
func TestWebSocketClient(t *testing.T) {
|
||
//发送webSocket请求
|
||
conn, resp, err := websocket.DefaultDialer.Dial(TestMTIMPushUrl, nil)
|
||
if err != nil {
|
||
fmt.Printf("连接失败:%v", err)
|
||
}
|
||
fmt.Printf("响应:%s", fmt.Sprint(resp))
|
||
//wsList = append(wsList, conn)
|
||
//关闭
|
||
conn.SetCloseHandler(func(code int, text string) error {
|
||
fmt.Printf("WebSocket connection closed with code %d and text: %s\n", code, text)
|
||
return nil
|
||
})
|
||
defer func(conn *websocket.Conn) {
|
||
err := conn.Close()
|
||
if err != nil {
|
||
return
|
||
}
|
||
}(conn)
|
||
|
||
//赋入全局变量
|
||
//Default(conn)
|
||
//生成clientID
|
||
clientID := GenClientId()
|
||
|
||
//创建实例连接
|
||
client := &Client{
|
||
ID: clientID,
|
||
//AccountId:conn. ,
|
||
Socket: conn,
|
||
HeartbeatTime: time.Now().Unix(),
|
||
}
|
||
//rdb.Set("testPush", client, 0)
|
||
|
||
//注册到连接管理
|
||
RegisterChan <- client
|
||
//todo 暂时不确定放哪
|
||
//go Start()
|
||
|
||
done := make(chan SingleChat)
|
||
//err = conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(time.Second))
|
||
err = conn.WriteMessage(websocket.TextMessage, []byte("~#HHHBBB#~"))
|
||
if err != nil {
|
||
fmt.Println(err)
|
||
}
|
||
|
||
for {
|
||
_, msg, err := conn.ReadMessage()
|
||
if err != nil {
|
||
//log.Fatal(err)
|
||
break
|
||
}
|
||
fmt.Printf("%s receive: %s\n", conn.RemoteAddr(), string(msg))
|
||
}
|
||
<-done
|
||
|
||
}
|
||
|
||
func TestPUSH(t *testing.T) {
|
||
key := "589:7954977:10"
|
||
//rdb.RPush(key, "1111111111")
|
||
//rdb.RPush(key, "{\"vendorID\":10,\"userID\":11158569333,\"NewMessageNum\":3,\"latestMsg\":\"hhhhhhhhhhh\",\"latestTime\":1681983980}")
|
||
//rdb.RPush(key, "{\"vendorID\":10,\"userID\":11158569333,\"NewMessageNum\":3,\"latestMsg\":\"oooooooooo\",\"latestTime\":1681983980}")
|
||
//rdb.RPush(key, "2222222222222")
|
||
rdb.RPush(key, "{\"vendorID\":10,\"userID\":11158569333,\"NewMessageNum\":4,\"latestMsg\":\"成功插入新数据,看下cnt\",\"latestTime\":1681983980}")
|
||
rdb.RPush(key, "{\"vendorID\":10,\"userID\":11158569333,\"NewMessageNum\":5,\"latestMsg\":\"成功插入新数据,看下cnt\",\"latestTime\":1681983980}")
|
||
}
|
||
|
||
//用户消息列表
|
||
type UserMessageList struct {
|
||
VendorID int `json:"vendorID"` //平台品牌 10-美团 11-饿了么
|
||
UserID int `json:"userID"` //用户ID
|
||
NewMessageNum int `json:"NewMessageNum"` //新消息数量
|
||
LatestMsg string `json:"latestMsg"` //最新一条消息
|
||
LatestTime int `json:"latestTime"` //最新一条消息发送时间
|
||
}
|
||
|
||
func TestNewRedis(t *testing.T) {
|
||
var flag = 11158569333
|
||
var key = "589:7954977:10"
|
||
s2 := rdb.LRange(key, 0, -1).Val()
|
||
fmt.Printf("before len %d\n", len(s2))
|
||
fmt.Printf("before ans %s\n", s2)
|
||
cnt := 0
|
||
n := rdb.Exists(key).Val()
|
||
if n > 0 {
|
||
for i := 0; i < len(s2); i++ {
|
||
v := UserMessageList{}
|
||
_ = json.Unmarshal([]byte(s2[i]), &v)
|
||
if v.UserID == flag {
|
||
rdb.LSet(key, int64(i), "del")
|
||
rdb.LRem(key, 0, "del")
|
||
s2 = append(s2[:i], s2[i+1:]...)
|
||
i--
|
||
if v.NewMessageNum == 0 { //目前为首条
|
||
cnt++ //赋值1
|
||
} else {
|
||
cnt = v.NewMessageNum
|
||
}
|
||
}
|
||
}
|
||
}
|
||
fmt.Printf("after cnt %d\n", cnt)
|
||
fmt.Printf("after len %d\n", len(s2))
|
||
fmt.Printf("after ans %s\n", s2)
|
||
//存入flag数据
|
||
ans := UserMessageList{
|
||
VendorID: 10,
|
||
UserID: 11158569333,
|
||
NewMessageNum: cnt,
|
||
LatestMsg: "成功插入新数据,看下cnt",
|
||
LatestTime: 1681983980,
|
||
}
|
||
param, _ := json.Marshal(ans)
|
||
rdb.RPush(key, param)
|
||
}
|
||
|
||
// 根据账号获取连接
|
||
func TestGetClient(t *testing.T) {
|
||
accountId := "QW+r2FtsRKGGLJnlgyDNlChzcKcSZ8Kfgh0qw//ONuQCDKzky4x+nlbnx3k1JX13"
|
||
clients := make([]*Client, 0)
|
||
|
||
Manager.mu.Lock()
|
||
defer Manager.mu.Unlock()
|
||
|
||
if len(Manager.Accounts[accountId]) > 0 {
|
||
for _, clientId := range Manager.Accounts[accountId] {
|
||
if c, ok := Manager.Clients[clientId]; ok {
|
||
clients = append(clients, c)
|
||
}
|
||
}
|
||
}
|
||
|
||
fmt.Printf(utils.Format4Output(clients, false))
|
||
}
|
||
func TestMal(t *testing.T) {
|
||
|
||
}
|