online.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package online
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. "github.com/gorilla/websocket"
  7. "github.com/patrickmn/go-cache"
  8. "github.com/sirupsen/logrus"
  9. "gogs.daxia.dev/huanan/pkg.daxia.dev/event2"
  10. "google.golang.org/protobuf/proto"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. "nn.daxia.dev/gameproto"
  13. "nn.daxia.dev/model"
  14. )
  15. type Msg struct {
  16. RoomID uint32
  17. Offset int
  18. NotifyType uint32
  19. Data string
  20. }
  21. type EventMsg struct {
  22. Msg Msg
  23. }
  24. type EventConnect struct {
  25. UserModel *model.User
  26. Conn *websocket.Conn
  27. }
  28. type EventDisconnect struct {
  29. UserModel *model.User
  30. Conn *websocket.Conn
  31. }
  32. type EventPing struct {
  33. UserModel *model.User
  34. Conn *websocket.Conn
  35. }
  36. type OnlineUser struct {
  37. UserID uint
  38. RoomID uint32
  39. ChairID uint32
  40. Conn *websocket.Conn
  41. Locker sync.Mutex
  42. IsRunning bool
  43. Ready bool
  44. Event chan bool
  45. MsgList []Msg
  46. MsgIndex int
  47. }
  48. func NewOnlineUser(userID uint, roomID, chairID uint32, conn *websocket.Conn) *OnlineUser {
  49. return &OnlineUser{
  50. UserID: userID,
  51. RoomID: roomID,
  52. ChairID: chairID,
  53. Conn: conn,
  54. Locker: sync.Mutex{},
  55. IsRunning: false,
  56. Ready: false,
  57. Event: make(chan bool),
  58. MsgList: make([]Msg, 0),
  59. MsgIndex: 0,
  60. }
  61. }
  62. func (p *OnlineUser) Start() {
  63. p.IsRunning = true
  64. //监听消息
  65. evnetUser := model.EventNotifyMsg + fmt.Sprintf("user_%d", p.UserID)
  66. event2.On[EventMsg](evnetUser, event2.ListenerFunc[EventMsg](func(e event2.Event[EventMsg]) error {
  67. p.Locker.Lock()
  68. defer p.Locker.Unlock()
  69. if !p.IsRunning {
  70. return nil
  71. }
  72. msg := e.Data().Msg
  73. p.MsgIndex = p.MsgIndex + 1
  74. msg.Offset = p.MsgIndex
  75. p.MsgList = append(p.MsgList, msg)
  76. logrus.Debugf("event ready send: %v", evnetUser)
  77. go func() {
  78. defer func() {
  79. recover()
  80. }()
  81. p.Event <- true
  82. }()
  83. return nil
  84. }))
  85. //退出则清理一下
  86. defer func() {
  87. //cancel event listener
  88. event2.On[EventMsg](evnetUser, event2.ListenerFunc[EventMsg](func(e event2.Event[EventMsg]) error {
  89. return nil
  90. }))
  91. p.Stop()
  92. }()
  93. for {
  94. if !p.IsRunning {
  95. break
  96. }
  97. <-p.Event
  98. if !p.Ready {
  99. continue
  100. }
  101. //遍历,发送通知
  102. sendMsgList := func() []Msg {
  103. p.Locker.Lock()
  104. defer p.Locker.Unlock()
  105. msgTmp := make([]Msg, len(p.MsgList))
  106. copy(msgTmp, p.MsgList)
  107. p.MsgList = make([]Msg, 0)
  108. return msgTmp
  109. }()
  110. for _, item := range sendMsgList {
  111. err := SendMsg(p.Conn, EmitData{
  112. UserID: p.UserID,
  113. NotifyType: gameproto.NotifyTypeEnum(item.NotifyType),
  114. Encrypt: false,
  115. Data: item.Data,
  116. })
  117. if err != nil {
  118. logrus.Error(err)
  119. return
  120. }
  121. }
  122. fmt.Println("running")
  123. }
  124. }
  125. func (p *OnlineUser) SetReady(msg Msg) {
  126. if !p.IsRunning {
  127. return
  128. }
  129. p.Locker.Lock()
  130. defer p.Locker.Unlock()
  131. p.Ready = true
  132. p.MsgIndex = 1
  133. msg.Offset = 1
  134. p.MsgList = make([]Msg, 0)
  135. p.MsgList = append(p.MsgList, msg)
  136. go func() {
  137. defer func() {
  138. recover()
  139. }()
  140. p.Event <- true
  141. }()
  142. }
  143. func (p *OnlineUser) Stop() {
  144. if !p.IsRunning {
  145. return
  146. }
  147. p.Locker.Lock()
  148. defer p.Locker.Unlock()
  149. p.IsRunning = false
  150. go func() {
  151. p.Event <- true
  152. close(p.Event)
  153. }()
  154. p.Conn.Close()
  155. }
  156. var OnlineUserCache = cache.New(time.Minute*3, 10*time.Minute)
  157. var locker = sync.Mutex{}
  158. func Init() {
  159. //删除的时候,取消
  160. OnlineUserCache.OnEvicted(func(key string, value interface{}) {
  161. onlineUser := value.(*OnlineUser)
  162. onlineUser.Stop()
  163. })
  164. event2.On[EventConnect](model.EventConnect, event2.ListenerFunc[EventConnect](func(e event2.Event[EventConnect]) error {
  165. userModel := e.Data().UserModel
  166. conn := e.Data().Conn
  167. Active(userModel.ID, conn)
  168. return nil
  169. }))
  170. event2.On[EventPing](model.EventPing, event2.ListenerFunc[EventPing](func(e event2.Event[EventPing]) error {
  171. userModel := e.Data().UserModel
  172. conn := e.Data().Conn
  173. Active(userModel.ID, conn)
  174. return nil
  175. }))
  176. event2.On[EventDisconnect](model.EventDisconnect, event2.ListenerFunc[EventDisconnect](func(e event2.Event[EventDisconnect]) error {
  177. userModel := e.Data().UserModel
  178. conn := e.Data().Conn
  179. UnActive(userModel.ID, conn)
  180. return nil
  181. }))
  182. }
  183. func Active(userID uint, conn *websocket.Conn) {
  184. //logrus.Infof("active user id:%d", userID)
  185. locker.Lock()
  186. defer locker.Unlock()
  187. var onlineUser *OnlineUser
  188. userKey := GetKey(userID)
  189. user, exists := OnlineUserCache.Get(userKey)
  190. if !exists {
  191. onlineUser = &OnlineUser{
  192. UserID: userID,
  193. RoomID: 0,
  194. ChairID: 0,
  195. Conn: conn,
  196. Locker: sync.Mutex{},
  197. IsRunning: false,
  198. Event: make(chan bool),
  199. MsgList: make([]Msg, 0),
  200. MsgIndex: 0,
  201. }
  202. go onlineUser.Start()
  203. OnlineUserCache.Set(userKey, onlineUser, time.Minute*3)
  204. } else {
  205. currConn := user.(*OnlineUser).Conn
  206. if currConn != conn {
  207. //TODO:发送掉线信息
  208. data, err := proto.Marshal(&gameproto.Disconnect{
  209. UserID: uint32(userID),
  210. })
  211. if err != nil {
  212. logrus.Error(err)
  213. return
  214. }
  215. SendMsg(currConn, EmitData{
  216. UserID: userID,
  217. NotifyType: gameproto.NotifyTypeEnum_NotifyTypeDisconnect,
  218. Encrypt: false,
  219. Data: string(data),
  220. })
  221. currConn.Close()
  222. user.(*OnlineUser).Conn = conn
  223. }
  224. OnlineUserCache.Set(userKey, user, time.Minute*3)
  225. }
  226. }
  227. func SetReady(userID uint, notifyType gameproto.NotifyTypeEnum, dataSend protoreflect.ProtoMessage) {
  228. locker.Lock()
  229. defer locker.Unlock()
  230. userKey := GetKey(userID)
  231. userObj, exists := OnlineUserCache.Get(userKey)
  232. if !exists {
  233. logrus.Error("用户不存在:", userID)
  234. return
  235. }
  236. data, err := proto.Marshal(dataSend)
  237. if err != nil {
  238. logrus.Error(err)
  239. return
  240. }
  241. user := userObj.(*OnlineUser)
  242. user.SetReady(Msg{
  243. NotifyType: uint32(notifyType),
  244. Data: string(data),
  245. })
  246. }
  247. func IsActive(userID uint) bool {
  248. locker.Lock()
  249. defer locker.Unlock()
  250. userKey := GetKey(userID)
  251. _, exists := OnlineUserCache.Get(userKey)
  252. return exists
  253. }
  254. func UnActive(userID uint, conn *websocket.Conn) {
  255. locker.Lock()
  256. defer locker.Unlock()
  257. userKey := GetKey(userID)
  258. user, exists := OnlineUserCache.Get(userKey)
  259. if !exists {
  260. return
  261. }
  262. currConn := user.(*OnlineUser).Conn
  263. if currConn != conn {
  264. return
  265. }
  266. OnlineUserCache.Delete(userKey)
  267. }
  268. func GetUserByRoom(roomID uint32) []uint32 {
  269. onlineUserIDList := make([]uint32, 0)
  270. roomModel := model.Room{}
  271. userList, err := roomModel.GetRoomUserList(roomID)
  272. if err != nil {
  273. logrus.Error(err)
  274. return onlineUserIDList
  275. }
  276. return userList
  277. }
  278. func GetUserByNotInRoom(roomID uint32) []uint32 {
  279. onlineUserIDList := make([]uint32, 0)
  280. locker.Lock()
  281. defer locker.Unlock()
  282. items := OnlineUserCache.Items()
  283. for _, item := range items {
  284. onlineUser := item.Object.(*OnlineUser)
  285. if onlineUser.RoomID == roomID {
  286. continue
  287. }
  288. onlineUserIDList = append(onlineUserIDList, uint32(onlineUser.UserID))
  289. }
  290. return onlineUserIDList
  291. }
  292. func GetAllUser() []uint32 {
  293. onlineUserIDList := make([]uint32, 0)
  294. locker.Lock()
  295. defer locker.Unlock()
  296. items := OnlineUserCache.Items()
  297. for _, item := range items {
  298. onlineUser := item.Object.(*OnlineUser)
  299. onlineUserIDList = append(onlineUserIDList, uint32(onlineUser.UserID))
  300. }
  301. return onlineUserIDList
  302. }
  303. func GetKey(userID uint) string {
  304. return fmt.Sprintf("online_user_%d", userID)
  305. }