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.

37 lines
775 B

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. })
  21. m.HandleMessage(func(session *melody.Session, msg []byte) {
  22. if err := session.Publish(msg); err != nil {
  23. log.Println(err)
  24. }
  25. })
  26. m.HandleSentMessage(func(session *melody.Session, bytes []byte) {
  27. log.Printf("%+v", session.Channel().Online())
  28. log.Printf("%+v", string(bytes))
  29. })
  30. router.Run(":8080")
  31. }