websocket.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package front
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. //"net/http"
  7. qutil "qfw/util"
  8. "qfw/util/redis"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/go-xweb/httpsession"
  13. "github.com/go-xweb/xweb"
  14. "golang.org/x/net/websocket"
  15. )
  16. //socket对象放在内存中,待rpc回调使用
  17. type Wss struct {
  18. Conn *websocket.Conn
  19. Time int64
  20. }
  21. type MapSocket struct {
  22. Map map[string]*Wss
  23. Lock sync.Mutex
  24. }
  25. func (m *MapSocket) GC() {
  26. defer qutil.Catch()
  27. m.Lock.Lock()
  28. now := time.Now().Unix()
  29. for k, v := range m.Map {
  30. if now-v.Time > 3600 || v.Conn == nil {
  31. delete(m.Map, k)
  32. }
  33. }
  34. m.Lock.Unlock()
  35. time.AfterFunc(5*time.Minute, m.GC)
  36. }
  37. var MSPOOL = 20
  38. var MapSocketArr = make([]*MapSocket, MSPOOL)
  39. //初始化
  40. func init() {
  41. for i := 0; i < MSPOOL; i++ {
  42. ms := &MapSocket{Map: map[string]*Wss{}}
  43. go ms.GC()
  44. MapSocketArr[i] = ms
  45. }
  46. }
  47. //根据代码和ws做映射
  48. func PutWsByCode(src string, ws *websocket.Conn) {
  49. defer qutil.Catch()
  50. n := HashVal(src) % MSPOOL
  51. ms := MapSocketArr[n]
  52. ms.Lock.Lock()
  53. ms.Map[src] = &Wss{ws, time.Now().Unix()}
  54. ms.Lock.Unlock()
  55. }
  56. //计算代码的hash值
  57. func HashVal(src string) int {
  58. check := 0
  59. for i := len(src) / 2; i < len(src); i++ {
  60. check += int(src[i])
  61. }
  62. return check
  63. }
  64. //rpc回调,写到前台
  65. func GetWsByCode(param []string) bool {
  66. if len(param) < 2 {
  67. return false
  68. }
  69. src := param[0]
  70. openid := param[1]
  71. if src == "" {
  72. return false
  73. }
  74. defer qutil.Catch()
  75. n := HashVal(src) % MSPOOL
  76. ms := MapSocketArr[n]
  77. defer func() {
  78. ms.Lock.Lock()
  79. delete(ms.Map, src)
  80. ms.Lock.Unlock()
  81. }()
  82. ms.Lock.Lock()
  83. wss := ms.Map[src]
  84. ms.Lock.Unlock()
  85. if wss != nil && wss.Conn != nil {
  86. infoData := LoginInfo(src, openid, wss.Conn.Sess)
  87. sendmessage, _ := json.Marshal(infoData)
  88. if err := websocket.Message.Send(wss.Conn, string(sendmessage)); err != nil {
  89. log.Println("socket send fail..", err)
  90. return false
  91. } else {
  92. wss.Conn.Close()
  93. }
  94. return true
  95. } else {
  96. return false
  97. }
  98. }
  99. //用户登录信息
  100. func LoginInfo(shareid, openid string, Sess interface{}) (infoData map[string]interface{}) {
  101. if Sess == nil {
  102. return nil
  103. }
  104. sess, _ := Sess.(*httpsession.Session)
  105. infoData = make(map[string]interface{})
  106. if openid != "" {
  107. sess.Set("openid", openid)
  108. redisheadimg := redis.Get("other", "newUser-"+openid)
  109. if redisheadimg == nil {
  110. redisheadimg = ""
  111. }
  112. user, _ := mongodb.FindOneByField("user", `{"s_m_openid":"`+openid+`"}`, `{"s_nickname":1,"s_headimage":1,"s_m_openid":1}`)
  113. if user != nil && len(*user) > 0 {
  114. infoData["result"] = "ok"
  115. infoData["s_nickname"] = fmt.Sprint((*user)["s_nickname"])
  116. infoData["s_headimage"] = fmt.Sprint((*user)["s_headimage"])
  117. infoData["redisheadimg"] = fmt.Sprint(redisheadimg)
  118. infoData["encryptId"] = se.EncodeString(qutil.BsonIdToSId((*user)["_id"]))
  119. infoData["shareid"] = shareid
  120. (*user)["shareid"] = shareid
  121. nick := fmt.Sprint((*user)["s_nickname"])
  122. sess.Set("nickname", nick)
  123. sess.Set("s_nickname", nick)
  124. sess.Set("s_m_openid", fmt.Sprint((*user)["s_m_openid"]))
  125. sess.Set("user", *user)
  126. }
  127. }
  128. return infoData
  129. }
  130. //登录关注
  131. func ServeWss(conn *websocket.Conn) {
  132. defer qutil.Catch()
  133. conn.Sess = xweb.RootApp().SessionManager.Session(conn.R, conn.W)
  134. var shareIds string
  135. for {
  136. var shareData string
  137. err := websocket.Message.Receive(conn, &shareData)
  138. if err != nil {
  139. //log.Println("前台socket关闭,后台socket断开并退出循环。。。。")
  140. break
  141. } else {
  142. //心跳监测
  143. if shareData == "HeartBeat" {
  144. websocket.Message.Send(conn, "HeartBeat")
  145. continue
  146. }
  147. shareIds = shareData
  148. shareidlist := strings.Split(shareIds, "___")
  149. if shareIds != "" && len(shareidlist) > 1 {
  150. shareidnum := shareidlist[0]
  151. shareidkop := shareidlist[1]
  152. PutWsByCode(se.DecodeString(shareidnum), conn)
  153. PutWsByCode(se.DecodeString(shareidkop), conn)
  154. websocket.Message.Send(conn, "ok")
  155. }
  156. }
  157. }
  158. }
  159. //实验室
  160. func QrToLabWss(conn *websocket.Conn) {
  161. defer qutil.Catch()
  162. var receive, userId string
  163. var qrToLab_ok, qrToLab_open_ok bool
  164. //接收消息
  165. go func() {
  166. defer qutil.Catch()
  167. for {
  168. err := websocket.Message.Receive(conn, &receive)
  169. if err != nil {
  170. receive = "close"
  171. log.Println("websocket接收失败!", err)
  172. return
  173. }
  174. if receive == "close" {
  175. return
  176. } else if receive != "close" { //接收到userid
  177. userId = se.DecodeString(receive)
  178. }
  179. }
  180. }()
  181. //发送消息
  182. for {
  183. time.Sleep(2 * time.Second)
  184. if receive == "close" { //接收到关闭信息
  185. conn.Close()
  186. return
  187. } else if userId == "" {
  188. continue
  189. }
  190. var reply string
  191. //是否进入实验室
  192. if !qrToLab_ok {
  193. qrToLab_ok, _ = redis.Exists("other", "qrToLab_"+userId)
  194. if qrToLab_ok {
  195. reply = "qrToLab_ok"
  196. }
  197. }
  198. //是否打开开关
  199. if !qrToLab_open_ok {
  200. qrToLab_open_ok, _ = redis.Exists("other", "qrToLab_open_"+userId)
  201. if qrToLab_open_ok {
  202. reply = "qrToLab_open_ok"
  203. }
  204. }
  205. if reply == "" {
  206. continue
  207. }
  208. sendmessage, _ := json.Marshal(reply)
  209. if err := websocket.Message.Send(conn, sendmessage); err != nil {
  210. redis.Del("other", "qrToLab_"+userId)
  211. redis.Del("other", "qrToLab_open_"+userId)
  212. //log.Println("websocket发送失败!", err)
  213. conn.Close()
  214. return
  215. }
  216. if reply == "qrToLab_ok" {
  217. redis.Del("other", "qrToLab_"+userId)
  218. } else if reply == "qrToLab_open_ok" {
  219. redis.Del("other", "qrToLab_open_"+userId)
  220. }
  221. if qrToLab_ok && qrToLab_open_ok {
  222. conn.Close()
  223. return
  224. }
  225. }
  226. }