websocket.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "flag"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. "sikey.com/websocket/config"
  9. "sikey.com/websocket/repositories"
  10. "sikey.com/websocket/server"
  11. "sikey.com/websocket/stackexchange"
  12. "sikey.com/websocket/utils/mysqlx"
  13. "sikey.com/websocket/utils/zlog"
  14. )
  15. var configFile = flag.String("f", "./etc/websocket.toml", "the config file")
  16. func main() {
  17. flag.Parse()
  18. config.MustLoadConfig(*configFile)
  19. // Zaplog init
  20. zlog.WithZapLogger(zlog.NewLogger(config.MustLoadLogger()))
  21. app := newApp()
  22. app.Run()
  23. }
  24. func newApp() *gin.Engine {
  25. app := gin.Default()
  26. // 创建 Websocket 横向拓展应用
  27. exc := stackexchange.NewStackExchange(
  28. config.Kafka.Brokers,
  29. config.Kafka.Topic,
  30. config.Kafka.Partition,
  31. config.Kafka.MaxBytes,
  32. )
  33. srv := &server.Server{
  34. Upgrader: websocket.Upgrader{
  35. ReadBufferSize: 1024,
  36. WriteBufferSize: 1024,
  37. CheckOrigin: func(r *http.Request) bool {
  38. return true
  39. },
  40. },
  41. WriteWait: 10 * time.Second,
  42. ReadWait: 10 * time.Second,
  43. PongWait: 20 * time.Second,
  44. // 写 ping 帧周期(必须小于 pongWait), 54s
  45. // PingWait: (600 * time.Second) * 9 / 10,
  46. // (pongWait * 9) / 10
  47. PingWait: 13 * time.Second,
  48. Hub: server.NewHub(server.HubConfig{
  49. ConnectSize: 1024,
  50. DisconnectSize: 1024,
  51. MessageSize: 125,
  52. StackExchange: exc,
  53. }),
  54. Repositories: repositories.NewRepositories(mysqlx.ConnectMysql()),
  55. }
  56. app.GET("/websocket/endpoint", func(ctx *gin.Context) { server.WebsocketHandler(ctx, srv) })
  57. return app
  58. }