// If listener is non-nil, then it's used; otherwise listen on TCP using the given port. func (s *Server) Start(port int, listener *net.TCPListener) error { if listener == nil { var err error ip, err := service.GetLocalIp() if err != nil { return err } addr := fmt.Sprintf("%s:%d", ip, port) tcpAddr, err := net.ResolveTCPAddr("tcp4", addr) if err != nil { return err } s.l.Println("Listening for debug TCP clients on", addr) listener, err = net.ListenTCP("tcp", tcpAddr) if err != nil { return err } } go func() { for { c, err := listener.AcceptTCP() if err != nil { continue } c.SetWriteDeadline(time.Now().Add(10 * time.Millisecond)) c.SetKeepAlive(true) c.SetKeepAlivePeriod(tcpKeepAlivePeriod) c.SetNoDelay(true) go s.tcpClientServer(c) } }() return nil }
func main() { flag.Parse() conf, err := internal.ParseConf() if err != nil { log.Fatal(err) } localIp, err := service.GetLocalIp() if err != nil { log.Fatal(err) } // 注册到LOOKUP服务 service.RegisterMoaService(&service.MoaServiceRegReq{ ServiceUri: fmt.Sprintf("/service/prism/%s", conf.Namespace), HostPort: fmt.Sprintf("%s:%d", localIp, conf.DebugPort), // redis是udp memcache是tcp Protocol: "redis", }) runtime.GOMAXPROCS(runtime.NumCPU()) log.Fatal(internal.NewServer(conf, os.Stdout).Listen(nil, nil, nil)) }
// Listen launches the various server goroutines and starts the various listeners. // If the listener params are nil, these are constructed from the parameters in the conf. Otherwise they are // used as-is. This makes it possible for the tests to construct listeners on an available port and pass them // in. func (s *Server) Listen(clientConn *net.UDPConn, forwardListener net.Listener, debugListener *net.TCPListener) error { go s.handleMetaStats() go s.flush() go s.aggregate() if s.conf.OSStats != nil { go s.checkOSStats() } if s.conf.Scripts != nil { go s.runScripts() } if s.conf.forwardingEnabled { s.forwardingIncoming = make(chan *Stat, incomingQueueSize) go s.flushForwarding() go s.aggregateForwarding() } errorCh := make(chan error) if s.conf.forwarderEnabled { if forwardListener == nil { l, err := net.Listen("tcp", s.conf.ForwarderListenAddr) if err != nil { return err } forwardListener = tcpKeepAliveListener{l.(*net.TCPListener)} } s.l.Println("Listening for forwarded gost messages on", forwardListener.Addr()) go s.aggregateForwarded() go func() { errorCh <- s.forwardServer(forwardListener) }() } if err := s.Start(s.conf.DebugPort, debugListener); err != nil { return err } if clientConn == nil { ip, err := service.GetLocalIp() if err != nil { return err } udpAddr := fmt.Sprintf("%s:%d", ip, s.conf.Port) udp, err := net.ResolveUDPAddr("udp", udpAddr) if err != nil { return err } clientConn, err = net.ListenUDP("udp", udp) if err != nil { return err } } s.l.Println("Listening for UDP client requests on", clientConn.LocalAddr()) go func() { errorCh <- s.clientServer(clientConn) }() // Indicate that we've started s.metaInc("server_start") return <-errorCh }