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.

62 lines
1.3 KiB

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