func NewTCPJSONHandler(a *giles.Archiver, addPort, queryPort, subscribePort int) *TCPJSONHandler { var err error t := &TCPJSONHandler{a: a, errors: make(chan error)} t.addAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(addPort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", addPort, err) } t.addConn, err = net.ListenTCP("tcp", t.addAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } t.queryAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(queryPort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", queryPort, err) } t.queryConn, err = net.ListenTCP("tcp", t.queryAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } t.subscribeAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(subscribePort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", subscribePort, err) } t.subscribeConn, err = net.ListenTCP("tcp", t.subscribeAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } return t }
func server_thread(wg_server *sync.WaitGroup) { defer wg_server.Done() server_state = RUNNING logger.Println("Launching server...") runtime.GOMAXPROCS(runtime.NumCPU()) tsp_task_manager.CreateTaskManager() // listen workers laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:5000") if nil != err { logger.Printf("ResolveTCPAddr (worker) error: %v\n", err) server_state = STOPPED return } listener, err := net.ListenTCP("tcp", laddr) if err != nil { logger.Printf("workers listen error: %v\n", err) server_state = STOPPED return } var wg_workers_accept sync.WaitGroup wg_workers_accept.Add(1) go accept_workers(listener, &wg_workers_accept) // listen clients laddr, err = net.ResolveTCPAddr("tcp", "127.0.0.1:6000") if nil != err { logger.Printf("ResolveTCPAddr (client) error: %v\n", err) server_state = STOPPED return } listener, err = net.ListenTCP("tcp", laddr) if err != nil { logger.Printf("clients listen error: %v\n", err) server_state = STOPPED return } var wg_clients_accept sync.WaitGroup wg_clients_accept.Add(1) go accept_clients(listener, &wg_clients_accept) logger.Println("Server work is started") // listen commands for { cmd := <-ch_cmd if cmd == SERVER_QUIT { // server quit server_state = STOPPED wg_workers_accept.Wait() wg_clients_accept.Wait() logger.Println("Server work is finished") return } } }
func main() { addr := ":8053" at, _ := net.ResolveTCPAddr("tcp6", addr) _, e := net.ListenTCP("tcp6", at) if e != nil { fmt.Printf("%s\n", e.Error()) } au, _ := net.ResolveTCPAddr("tcp4", addr) _, e = net.ListenTCP("tcp4", au) if e != nil { fmt.Printf("%s\n", e.Error()) } }
func (fileServer *FileServer) startServer() { tcpaddr, err := net.ResolveTCPAddr("tcp", "localhost:"+strconv.Itoa(fileServer.Port)) fileServer.check(err) if fileServer.Rf.Isdown == 1 { fileServer.Rf.Isdown = 0 fmt.Printf("Node %d up again\n", fileServer.Rf.Id()) fileServer.Rf.Up() if len(fileServer.NeedClose) != 0 { <-fileServer.NeedClose } if len(fileServer.CloseAll) != 0 { <-fileServer.CloseAll } time.Sleep(10 * time.Second) } tcp_acceptor, err := net.ListenTCP("tcp", tcpaddr) fileServer.check(err) defer tcp_acceptor.Close() go fileServer.backEnd() go fileServer.Rf.ProcessEvents() for { if len(fileServer.CloseAll) != 0 { fileServer.Rf.Shutdown() break } else if fileServer.Rf.IsClosedRaft() { break } else { for len(fileServer.CloseAll) == 0 && fileServer.Rf.LeaderId() != fileServer.Id { if tcp_acceptor != nil { tcp_acceptor.Close() tcp_acceptor = nil } time.Sleep(1 * time.Second) } if len(fileServer.CloseAll) != 0 { fileServer.Rf.Shutdown() break } else if fileServer.Rf.IsClosedRaft() { break } if tcp_acceptor == nil { tcp_acceptor, err = net.ListenTCP("tcp", tcpaddr) fileServer.check(err) } tcp_conn, err := tcp_acceptor.AcceptTCP() fileServer.check(err) go fileServer.serve(tcp_conn) } } tcp_acceptor.Close() }
func setupSocket(socket_version int, service string, config_obj *read_config.ReadConfig) error { socket_type := "tcp4" if socket_version == 6 { socket_type = "tcp6" } tcpAddr, err := net.ResolveTCPAddr(socket_type, service) common.CheckError(err) listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { return err } for { if conn, err := listener.Accept(); err != nil { continue } else { // run as a goroutine go handleClient(conn, config_obj) } } return nil }
//----------------------------------------------- HUB start func HubStart() { log.Println("Starting HUB") // start db StartDB() // data init startup_work() // Listen service := ":9090" config := cfg.Get() if config["hub_service"] != "" { service = config["hub_service"] } log.Println("Hub Service:", service) tcpAddr, err := net.ResolveTCPAddr("tcp4", service) checkError(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) for { conn, err := listener.Accept() if err != nil { continue } go handleClient(conn) } }
// ListenAndServe starts a nameserver on the configured address in *Server. func (srv *Server) ListenAndServe() error { addr := srv.Addr if addr == "" { addr = ":domain" } switch srv.Net { case "tcp", "tcp4", "tcp6": a, e := net.ResolveTCPAddr(srv.Net, addr) if e != nil { return e } l, e := net.ListenTCP(srv.Net, a) if e != nil { return e } return srv.serveTCP(l) case "udp", "udp4", "udp6": a, e := net.ResolveUDPAddr(srv.Net, addr) if e != nil { return e } l, e := net.ListenUDP(srv.Net, a) if e != nil { return e } return srv.serveUDP(l) } return &Error{err: "bad network"} }
func listen(healthCheckAddr chan net.Addr) error { addr, err := generateHealthCheckAddr() if err != nil { return err } listener, err := net.ListenTCP("tcp", addr.(*net.TCPAddr)) if err != nil { return err } healthCheckAddr <- listener.Addr() for { conn, err := listener.AcceptTCP() if err != nil { log.Fatal(err) } go func() { defer conn.Close() if !readHealth(conn) || !sendHealth(conn) { // Connection is dead with client return } }() } return nil }
// ListenTCP announces on the local network address laddr. The network net must // be: "tcp", "tcp4" or "tcp6". It returns an inherited net.Listener for the // matching network and address, or creates a new one using net.ListenTCP. func (n *Net) ListenTCP(nett string, laddr *net.TCPAddr) (*net.TCPListener, error) { if err := n.inherit(); err != nil { return nil, err } n.mutex.Lock() defer n.mutex.Unlock() // look for an inherited listener for i, l := range n.inherited { if l == nil { // we nil used inherited listeners continue } if isSameAddr(l.Addr(), laddr) { n.inherited[i] = nil n.active = append(n.active, l) return l.(*net.TCPListener), nil } } // make a fresh listener l, err := net.ListenTCP(nett, laddr) if err != nil { return nil, err } n.active = append(n.active, l) return l, nil }
func (s *Server) init() { if s.ReadBufferSize == 0 { s.ReadBufferSize = defaultReadBufferSize } if s.WriteBufferSize == 0 { s.WriteBufferSize = defaultWriteBufferSize } if s.OSReadBufferSize == 0 { s.OSReadBufferSize = defaultOSReadBufferSize } if s.OSWriteBufferSize == 0 { s.OSWriteBufferSize = defaultOSWriteBufferSize } listenAddr, err := net.ResolveTCPAddr("tcp", s.ListenAddr) if err != nil { log.Fatalf("Cannot resolve listenAddr=[%s]: [%s]", s.ListenAddr, err) } s.listenSocket, err = net.ListenTCP("tcp", listenAddr) if err != nil { log.Fatalf("Cannot listen for ListenAddr=[%s]: [%s]", listenAddr, err) } s.done = &sync.WaitGroup{} s.done.Add(1) }
func (server *tcpServer) Start() error { port := portStart for { tcpAddr, err := net.ResolveTCPAddr("tcp4", ":"+strconv.Itoa(port)) if err != nil { return err } server.listener, err = net.ListenTCP("tcp", tcpAddr) if err == nil { break } if port > portEnd { return errors.New(fmt.Sprintf("Port number exceedes %v", portEnd)) } port++ } //fmt.Printf("PortNumber = %v\n", port) server.port = strconv.Itoa(port) go func() { for { acceptNext := server.acceptCycle() if !acceptNext { return } } }() return nil }
func runMetadataService(cmd *cobra.Command, args []string) (exit int) { signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM) stderr.Print("metadata service starting...") unixl, err := unixListener() if err != nil { stderr.Error(err) return 1 } defer unixl.Close() tcpl, err := net.ListenTCP("tcp4", &net.TCPAddr{Port: flagListenPort}) if err != nil { stderr.PrintE(fmt.Sprintf("error listening on port %v", flagListenPort), err) return 1 } defer tcpl.Close() if err := initCrypto(); err != nil { stderr.Error(err) return 1 } go runRegistrationServer(unixl) go runPublicServer(tcpl) stderr.Print("metadata service running...") <-exitCh stderr.Print("metadata service exiting...") return }
func (r *SrsServer) Serve() error { // too many open files will thows a panic. addr, err := net.ResolveTCPAddr("tcp", r.addr) if err != nil { glog.Errorf("resolve listen address failed, err=%v", err) return fmt.Errorf("resolve listen address failed, err=%v", err) } var listener *net.TCPListener listener, err = net.ListenTCP("tcp", addr) if err != nil { glog.Errorf("listen failed, err=%v", err) return fmt.Errorf("listen failed, err=%v", err) } defer listener.Close() for { glog.Info("listener ready to accept client") conn, err := listener.AcceptTCP() if err != nil { glog.Errorf("accept client failed, err=%v", err) return fmt.Errorf("accept client failed, err=%v", err) } glog.Info("TCP Connected") go r.serve(conn) } }
func testPort() string { add, _ := net.ResolveTCPAddr("tcp", ":0") l, _ := net.ListenTCP("tcp", add) defer l.Close() port := strconv.Itoa(l.Addr().(*net.TCPAddr).Port) return port }
func (r *resolver) SetupFunc(port int) func() { return (func() { var err error // DNS operates primarily on UDP addr := &net.UDPAddr{ IP: net.ParseIP(r.listenAddress), Port: port, } r.conn, err = net.ListenUDP("udp", addr) if err != nil { r.err = fmt.Errorf("error in opening name server socket %v", err) return } // Listen on a TCP as well tcpaddr := &net.TCPAddr{ IP: net.ParseIP(r.listenAddress), Port: port, } r.tcpListen, err = net.ListenTCP("tcp", tcpaddr) if err != nil { r.err = fmt.Errorf("error in opening name TCP server socket %v", err) return } r.err = nil }) }
func NewTCPServer(t lotf.Tail, addr *net.TCPAddr) (*StreamServer, error) { listener, err := net.ListenTCP("tcp", addr) if err != nil { return nil, err } return &StreamServer{t, listener, make(chan bool, 1)}, nil }
func (ch *HandleClient) run() { ch.ExitWaitGr.Add(2) ch.raftnode.StartRaftNodes() address, _ := net.ResolveTCPAddr("tcp", ch.Address+":"+strconv.Itoa(ch.Port)) accept, _ := net.ListenTCP("tcp", address) go ch.handleCommit() go func() { for { tcp_conn, _ := accept.AcceptTCP() ch.ExitWaitGr.Add(1) go ch.serve(tcp_conn) } ch.ExitWaitGr.Done() }() }
func main() { logIt("SETUP", "Starting...") addr, err := net.ResolveTCPAddr("ip4", ":4848") errorCheck(err, "Problem resolving TCP address") listen, err := net.ListenTCP("tcp", addr) errorCheck(err, "TCP listening error") logIt("SETUP", "Ready.") for { connection, err := listen.Accept() if err != nil { continue } logIt("CONNECTION", "Got new connection") go newClient(connection) } os.Exit(0) }
func (cli *Client) listen() { defer cli.wg.Done() ln, err := net.ListenTCP("tcp", cli.app.laddr) if err != nil { Panic("listen failed:%v", err) } for { conn, err := ln.AcceptTCP() if err != nil { Log("acceept failed:%s", err.Error()) if opErr, ok := err.(*net.OpError); ok { if !opErr.Temporary() { break } } continue } Info("new connection from %v", conn.RemoteAddr()) hub := cli.fetchHub() if hub == nil { Error("no active hub") conn.Close() continue } conn.SetKeepAlive(true) conn.SetKeepAlivePeriod(time.Second * 60) go cli.handleConn(hub, conn) } }
func CreateListener(flags *TorrentFlags) (listener net.Listener, externalPort int, err error) { nat, err := CreatePortMapping(flags) if err != nil { err = fmt.Errorf("Unable to create NAT: %v", err) return } listenPort := flags.Port if nat != nil { var external net.IP if external, err = nat.GetExternalAddress(); err != nil { err = fmt.Errorf("Unable to get external IP address from NAT: %v", err) return } log.Println("External ip address: ", external) if listenPort, err = chooseListenPort(nat, listenPort); err != nil { log.Println("Could not choose listen port.", err) log.Println("Peer connectivity will be affected.") } } listener, err = net.ListenTCP("tcp", &net.TCPAddr{Port: listenPort}) if err != nil { log.Fatal("Listen failed:", err) } log.Println("Listening for peers on port:", listenPort) externalPort = listenPort return }
// Main function func main() { loadConfig() loadDict3() fingertable = make(map[int]NodeInfo) next = 0 if entrypt == "null" { createChordRing() } else { joinChordRing(entrypt) } stabilize() check_predecessor() fixFingers() getDict3FromSuccessor() dic3 := new(DIC3) rpc.Register(dic3) tcpAddr, err := net.ResolveTCPAddr(protocol, port) checkError(err) fmt.Println("Server started........") listener, err := net.ListenTCP(protocol, tcpAddr) checkError(err) for { conn, err := listener.Accept() if err != nil { continue } jsonrpc.ServeConn(conn) } }
func main() { flag.Parse() // Scan the arguments list if *versionFlag { fmt.Println("Version:", APP_VERSION) } service := ":" + strconv.FormatInt(*serverPort, 10) tcpAddr, err := net.ResolveTCPAddr("ip4", service) checkError(err) listener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) for { conn, err := listener.Accept() if err != nil { continue } stop := false for !stop { buf := make([]byte, 100) n, err := conn.Read(buf[0:]) if err != nil { stop = true } fmt.Fprintf(conn, "HTTP/1.0 200 OK\r\n\r\n") os.Stdout.Write(buf[0:n]) } conn.Close() } }
func (self *TcpInput) Init(pcf *plugins.PluginCommonConfig, conf toml.Primitive) (err error) { log.Println("TcpInput Init") self.common = pcf self.config = &TcpInputConfig{ Net: "tcp", } if err := toml.PrimitiveDecode(conf, self.config); err != nil { return fmt.Errorf("Can't unmarshal TcpInput config: %s", err) } address, err := net.ResolveTCPAddr(self.config.Net, self.config.Address) if err != nil { return fmt.Errorf("ResolveTCPAddress failed: %s\n", err.Error()) } self.listener, err = net.ListenTCP(self.config.Net, address) if err != nil { return fmt.Errorf("ListenTCP failed: %s\n", err.Error()) } // We're already listening, make sure we clean up if init fails later on. closeIt := true defer func() { if closeIt { self.listener.Close() } }() if self.config.KeepAlivePeriod != 0 { self.keepAliveDuration = time.Duration(self.config.KeepAlivePeriod) * time.Second } self.stopChan = make(chan bool) closeIt = false return nil }
func (me *ServerManager) setupListener(port int) { portStr := strconv.Itoa(port) addr, err := net.ResolveTCPAddr("tcp", "0.0.0.0:"+portStr) if err != nil { log.Print("Could not resolve port and listen address:", err) return } // listen on port go func() { l, err := net.ListenTCP("tcp", addr) if err != nil { log.Print("Could not listen for TCP connection:", err) } else { for { conn, err := l.AcceptTCP() if err != nil { log.Print("Could not accept TCP connection:", err) } else { // connection accepted // spinup machine me.Spinup() // close existing connection, not doing anything with it conn.Close() } } } }() }
func (this *SyslogProducer) startTCPServer() { Trace(this, "Starting TCP server") tcpAddr, err := net.ResolveTCPAddr("tcp", this.config.TCPAddr) if err != nil { panic(err) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil { panic(err) } closeChannel := make(chan bool, 1) this.closeChannels = append(this.closeChannels, closeChannel) go func() { for { select { case <-closeChannel: return default: } connection, err := listener.Accept() if err != nil { return } this.scan(connection) } }() Infof(this, "Listening for messages at TCP %s", this.config.TCPAddr) }
// ListenOnLocalRandomPort returns a TCP listener on a random // localhost port. func ListenOnLocalRandomPort() (net.Listener, error) { ip, err := Localhost() if err != nil { return nil, err } return net.ListenTCP("tcp", &net.TCPAddr{IP: ip, Port: 0}) }
func accepts() { strPort := "localhost:" + strconv.Itoa(port) fmt.Println("open port", strPort) addr, err := net.ResolveTCPAddr("tcp4", strPort) l, err := net.ListenTCP("tcp4", addr) if err != nil { fmt.Println(">>>> listen failed: ", err.Error()) return } addr = nil for { fmt.Println("Accept ready") session, err := l.AcceptTCP() if err != nil { //return fmt.Println("Accept error:", err.Error()) continue } go session_process(session) session = nil } l = nil }
func Start() { tcpAddr, err := net.ResolveTCPAddr("tcp4", PORT) checkError(err) tcpListener, err := net.ListenTCP("tcp", tcpAddr) checkError(err) fmt.Printf("cool server start \n") for { conn, err := tcpListener.Accept() fmt.Printf("accpet one connection! \n") checkError(err) go ConnHandle(conn) } }
func NewTestServer(t testing.TB, protocol uint8) *TestServer { laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } listen, err := net.ListenTCP("tcp", laddr) if err != nil { t.Fatal(err) } headerSize := 8 if protocol > protoVersion2 { headerSize = 9 } srv := &TestServer{ Address: listen.Addr().String(), listen: listen, t: t, protocol: protocol, headerSize: headerSize, quit: make(chan struct{}), } go srv.serve() return srv }
func ProxyRelay(port string, relays map[string]Relay) error { tcpAddr := net.TCPAddr{} tcpAddr.IP = net.ParseIP("127.0.0.1") tcpAddr.Port, _ = strconv.Atoi(port) ln, err := net.ListenTCP("tcp", &tcpAddr) if err != nil { msg := fmt.Sprintf("Proxy listener error on port %s: %s", port, err) LogWriter.Err(msg) return fmt.Errorf(msg) } msg := fmt.Sprintf("Started proxy listener on port: %s", port) LogWriter.Info(msg) defer ln.Close() for { conn, err := ln.AcceptTCP() if err != nil { msg := fmt.Sprintf("Error accepting TCP connection on port %s: %s", port, err) LogWriter.Err(msg) continue } conn.SetKeepAlive(true) if err != nil { msg := fmt.Sprintf("Error setting keep-alive on connection: %s", err) LogWriter.Err(msg) } go acceptClient(conn, relays) } return nil }