websocket 增加多分组 fork https://github.com/olahol/melody
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.

45 lines
976 B

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package main
  2. import (
  3. "log"
  4. "melody"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. m := melody.New()
  9. router := gin.Default()
  10. router.GET("/chat", func(context *gin.Context) {
  11. if err := m.HandleRequest(context.Writer, context.Request); err != nil {
  12. log.Println(err)
  13. }
  14. })
  15. m.HandleConnect(func(session *melody.Session) {
  16. ch := session.Request.URL.Query().Get("channel")
  17. if err := session.Subscribe(ch); err != nil {
  18. log.Println(err)
  19. }
  20. session.Set("channel", ch)
  21. })
  22. m.HandleMessage(func(session *melody.Session, msg []byte) {
  23. channel, ok1 := session.Get("channel")
  24. if ok1 {
  25. _ = m.BroadcastFilter(msg, func(s *melody.Session) bool {
  26. ch, ok2 := s.Get("channel")
  27. if ok2 && ch.(string) == channel.(string) {
  28. return true
  29. }
  30. return false
  31. })
  32. }
  33. })
  34. m.HandleSentMessage(func(session *melody.Session, bytes []byte) {
  35. log.Printf("%+v", session.Channel().Online())
  36. log.Printf("%+v", string(bytes))
  37. })
  38. router.Run(":8080")
  39. }