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.

64 lines
1.3 KiB

9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
  1. package main
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. "sync"
  7. "github.com/gin-gonic/gin"
  8. "github.com/olahol/melody"
  9. )
  10. // GopherInfo contains information about the gopher on screen
  11. type GopherInfo struct {
  12. ID, X, Y string
  13. }
  14. func main() {
  15. router := gin.Default()
  16. mrouter := melody.New()
  17. gophers := make(map[*melody.Session]*GopherInfo)
  18. lock := new(sync.Mutex)
  19. counter := 0
  20. router.GET("/", func(c *gin.Context) {
  21. http.ServeFile(c.Writer, c.Request, "index.html")
  22. })
  23. router.GET("/ws", func(c *gin.Context) {
  24. mrouter.HandleRequest(c.Writer, c.Request)
  25. })
  26. mrouter.HandleConnect(func(s *melody.Session) {
  27. lock.Lock()
  28. for _, info := range gophers {
  29. s.Write([]byte("set " + info.ID + " " + info.X + " " + info.Y))
  30. }
  31. gophers[s] = &GopherInfo{strconv.Itoa(counter), "0", "0"}
  32. s.Write([]byte("iam " + gophers[s].ID))
  33. counter++
  34. lock.Unlock()
  35. })
  36. mrouter.HandleDisconnect(func(s *melody.Session) {
  37. lock.Lock()
  38. mrouter.BroadcastOthers([]byte("dis "+gophers[s].ID), s)
  39. delete(gophers, s)
  40. lock.Unlock()
  41. })
  42. mrouter.HandleMessage(func(s *melody.Session, msg []byte) {
  43. p := strings.Split(string(msg), " ")
  44. lock.Lock()
  45. info := gophers[s]
  46. if len(p) == 2 {
  47. info.X = p[0]
  48. info.Y = p[1]
  49. mrouter.BroadcastOthers([]byte("set "+info.ID+" "+info.X+" "+info.Y), s)
  50. }
  51. lock.Unlock()
  52. })
  53. router.Run(":5000")
  54. }