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.

44 lines
696 B

10 years ago
10 years ago
10 years ago
  1. package main
  2. import (
  3. "../../"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-fsnotify/fsnotify"
  6. "io/ioutil"
  7. "net/http"
  8. )
  9. func main() {
  10. file := "file.txt"
  11. r := gin.Default()
  12. m := melody.New()
  13. w, _ := fsnotify.NewWatcher()
  14. r.GET("/", func(c *gin.Context) {
  15. http.ServeFile(c.Writer, c.Request, "index.html")
  16. })
  17. r.GET("/ws", func(c *gin.Context) {
  18. m.HandleRequest(c.Writer, c.Request)
  19. })
  20. m.HandleConnect(func(s *melody.Session) {
  21. content, _ := ioutil.ReadFile(file)
  22. s.Write(content)
  23. })
  24. go func() {
  25. for {
  26. ev := <-w.Events
  27. if ev.Op == fsnotify.Write {
  28. content, _ := ioutil.ReadFile(ev.Name)
  29. m.Broadcast(content)
  30. }
  31. }
  32. }()
  33. w.Add(file)
  34. r.Run(":5000")
  35. }