コード例 #1
1
ファイル: main.go プロジェクト: insionng/supervisorgo
func run(s service.Service, m *supervisorgo.Manager, u *url.URL) int {
	var err error
	var l net.Listener
	path := jsonrpc.DefaultRPCPath
	switch u.Scheme {
	case "unix":
		l, err = net.Listen(u.Scheme, u.Opaque+u.Path)
		if l != nil {
			defer os.Remove(u.Opaque + u.Path)
		}
	case "http":
		l, err = net.Listen("tcp", u.Host)
		path = u.Path
	default:
		err = fmt.Errorf("not supported scheme: %s", u.Scheme)
	}
	if err != nil {
		log.Println(err)
		return 1
	}
	m.HTTPServe(path)
	go http.Serve(l, nil)

	err = s.Run()
	if err != nil {
		log.Println(err)
		return 1
	}
	return 0
}
コード例 #2
1
ファイル: main.go プロジェクト: KayoticSully/syncthing
// getFreePort returns a free TCP port fort listening on. The ports given are
// tried in succession and the first to succeed is returned. If none succeed,
// a random high port is returned.
func getFreePort(host string, ports ...int) (int, error) {
	for _, port := range ports {
		c, err := net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
		if err == nil {
			c.Close()
			return port, nil
		}
	}

	c, err := net.Listen("tcp", host+":0")
	if err != nil {
		return 0, err
	}
	addr := c.Addr().String()
	c.Close()

	_, portstr, err := net.SplitHostPort(addr)
	if err != nil {
		return 0, err
	}

	port, err := strconv.Atoi(portstr)
	if err != nil {
		return 0, err
	}

	return port, nil
}
コード例 #3
1
ファイル: scgi.go プロジェクト: puzhengwu/goweb
func (s *Server) listenAndServeScgi(addr string) error {

	var l net.Listener
	var err error

	//if the path begins with a "/", assume it's a unix address
	if strings.HasPrefix(addr, "/") {
		l, err = net.Listen("unix", addr)
	} else {
		l, err = net.Listen("tcp", addr)
	}

	//save the listener so it can be closed
	s.l = l

	if err != nil {
		s.Logger.Println("SCGI listen error", err.Error())
		return err
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			s.Logger.Println("SCGI accept error", err.Error())
			return err
		}
		go s.handleScgiRequest(fd)
	}
	return nil
}
コード例 #4
1
ファイル: bind.go プロジェクト: tiare-lava/lavatrace
func listenTo(bind string) (net.Listener, error) {
	if strings.Contains(bind, ":") {
		return net.Listen("tcp", bind)
	} else if strings.HasPrefix(bind, ".") || strings.HasPrefix(bind, "/") {
		return net.Listen("unix", bind)
	} else if strings.HasPrefix(bind, "fd@") {
		fd, err := strconv.Atoi(bind[3:])
		if err != nil {
			return nil, fmt.Errorf("error while parsing fd %v: %v",
				bind, err)
		}
		f := os.NewFile(uintptr(fd), bind)
		defer f.Close()
		return net.FileListener(f)
	} else if strings.HasPrefix(bind, "einhorn@") {
		fd, err := strconv.Atoi(bind[8:])
		if err != nil {
			return nil, fmt.Errorf(
				"error while parsing einhorn %v: %v", bind, err)
		}
		return einhornBind(fd)
	}

	return nil, fmt.Errorf("error while parsing bind arg %v", bind)
}
コード例 #5
1
func (s *S) TestReconnect(c *C) {
	l, err := net.Listen("tcp", ":0")
	c.Assert(err, IsNil)
	err = l.Close()
	c.Assert(err, IsNil)

	msgc := make(chan *rfc5424.Message)
	handler := func(msg *rfc5424.Message) {
		msgc <- msg
	}

	addr := l.Addr().String()
	_, err = s.discd.AddServiceAndRegister("test-reconnect", addr)
	c.Assert(err, IsNil)

	donec := make(chan struct{})
	defer close(donec)

	sc, err := connect(s.discd, "test-reconnect", donec)
	c.Assert(err, IsNil)

	l, err = net.Listen("tcp", addr)
	c.Assert(err, IsNil)
	go runServer(l, handler)

	want := rfc5424.NewMessage(&rfc5424.Header{Version: 1}, []byte("test message"))
	_, err = sc.Write(rfc6587.Bytes(want))
	c.Assert(err, IsNil)

	c.Assert(<-msgc, DeepEquals, want)
}
コード例 #6
1
ファイル: server.go プロジェクト: anthonybrown/caddy
// Listen creates an active listener for s that can be
// used to serve requests.
func (s *Server) Listen() (net.Listener, error) {
	if s.Server == nil {
		return nil, fmt.Errorf("Server field is nil")
	}

	ln, err := net.Listen("tcp", s.Server.Addr)
	if err != nil {
		var succeeded bool
		if runtime.GOOS == "windows" {
			// Windows has been known to keep sockets open even after closing the listeners.
			// Tests reveal this error case easily because they call Start() then Stop()
			// in succession. TODO: Better way to handle this? And why limit this to Windows?
			for i := 0; i < 20; i++ {
				time.Sleep(100 * time.Millisecond)
				ln, err = net.Listen("tcp", s.Server.Addr)
				if err == nil {
					succeeded = true
					break
				}
			}
		}
		if !succeeded {
			return nil, err
		}
	}

	// Very important to return a concrete caddy.Listener
	// implementation for graceful restarts.
	return ln.(*net.TCPListener), nil
}
コード例 #7
0
func (l *LoginServer) Init() {
	var err error

	// Connect to our database
	l.databaseSession, err = mgo.Dial(l.config.LoginServer.Database.Host + ":" + strconv.Itoa(l.config.LoginServer.Database.Port))
	if err != nil {
		panic("Couldn't connect to the database server")
	} else {
		fmt.Println("Successfully connected to the database server")
	}

	// Select the appropriate database
	l.database = l.databaseSession.DB(l.config.LoginServer.Database.Name)

	// Listen for client connections
	l.clientsListener, err = net.Listen("tcp", ":2106")
	if err != nil {
		fmt.Println("Couldn't initialize the Login Server (Clients listener)")
	} else {
		fmt.Println("Login Server listening for clients connections on port 2106")
	}

	// Listen for game servers connections
	l.gameServersListener, err = net.Listen("tcp", ":9413")
	if err != nil {
		fmt.Println("Couldn't initialize the Login Server (Gameservers listener)")
	} else {
		fmt.Println("Login Server listening for gameservers connections on port 9413")
	}
}
コード例 #8
0
ファイル: app.go プロジェクト: RunCross/moonmq
func NewAppWithConfig(cfg *Config) (*App, error) {
	app := new(App)

	app.cfg = cfg

	var err error

	app.listener, err = net.Listen(getNetType(cfg.Addr), cfg.Addr)
	if err != nil {
		return nil, err
	}

	if len(cfg.HttpAddr) > 0 {
		app.httpListener, err = net.Listen(getNetType(cfg.HttpAddr), cfg.HttpAddr)
		if err != nil {
			return nil, err
		}
	}

	app.qs = newQueues(app)

	app.ms, err = OpenStore(cfg.Store, cfg.StoreConfig)
	if err != nil {
		return nil, err
	}

	return app, nil
}
コード例 #9
0
ファイル: server.go プロジェクト: Tiesheng/harbour
func (s *Server) newServer(proto, addr string) (*HttpServer, error) {
	switch proto {
	case "tcp":
		l, err := net.Listen("tcp", addr)
		if err != nil {
			return nil, err
		}
		return &HttpServer{&http.Server{Addr: addr, Handler: s.router}, l}, nil
	case "unix":
		os.Remove(addr)
		l, err := net.Listen("unix", addr)
		if err != nil {
			return nil, err
		}
		if err := setSocketGroup(addr, engine.SocketGroup); err != nil {
			l.Close()
			return nil, err
		}
		if err := os.Chmod(addr, 0660); err != nil {
			l.Close()
			return nil, err
		}
		return &HttpServer{&http.Server{Addr: addr, Handler: s.router}, l}, nil
	default:
		return nil, fmt.Errorf("Invalid protocol format.")
	}
}
コード例 #10
0
ファイル: fdcount_test.go プロジェクト: 2722/lantern
func TestTCP(t *testing.T) {
	// Lower maxAssertAttempts to keep this test from running too long
	maxAssertAttempts = 2

	l0, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		if err := l0.Close(); err != nil {
			t.Fatalf("Unable to close listener: %v", err)
		}
	}()

	start, fdc, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}
	assert.Equal(t, 1, start, "Starting count should have been 1")

	err = fdc.AssertDelta(0)
	if err != nil {
		t.Fatal(err)
	}
	assert.NoError(t, err, "Initial TCP count should be 0")

	l, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatal(err)
	}
	_, middle, err := Matching("TCP")
	if err != nil {
		t.Fatal(err)
	}

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.True(t, len(err.Error()) > 100)
	}
	err = fdc.AssertDelta(1)
	assert.NoError(t, err, "Ending TCP count should be 1")

	err = fdc.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have 1")
		assert.Contains(t, err.Error(), "New")
		assert.True(t, len(err.Error()) > 100)
	}

	if err := l.Close(); err != nil {
		t.Fatalf("Unable to close listener: %v", err)
	}
	err = middle.AssertDelta(0)
	if assert.Error(t, err, "Asserting wrong count should fail") {
		assert.Contains(t, err.Error(), "Expected 0, have -1")
		assert.Contains(t, err.Error(), "Removed")
		assert.True(t, len(err.Error()) > 100)
	}
}
コード例 #11
0
ファイル: test_proxy.go プロジェクト: keshavdv/subway
func main() {
	a, _ := net.Listen("tcp", ":0")
	defer a.Close()
	log.Println(a.Addr())

	b, _ := net.Listen("tcp", ":0")
	defer b.Close()
	log.Println(b.Addr())

	conn1, err := a.Accept()
	if err != nil {
		// handle error
		log.Println("err")
	}

	conn2, err := b.Accept()
	if err != nil {
		// handle error
		log.Println("err")
	}

	log.Println("Starting proxy")
	proxy.Proxy(conn1, conn2)

}
コード例 #12
0
ファイル: grpclb_test.go プロジェクト: ruinanchen/grpc-go
func TestDropRequestFailedNonFailFast(t *testing.T) {
	// Start a backend.
	beLis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatalf("Failed to listen %v", err)
	}
	beAddr := strings.Split(beLis.Addr().String(), ":")
	bePort, err := strconv.Atoi(beAddr[1])
	backends := startBackends(t, besn, beLis)
	defer stopBackends(backends)

	// Start a load balancer.
	lbLis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		t.Fatalf("Failed to create the listener for the load balancer %v", err)
	}
	lbCreds := &serverNameCheckCreds{
		sn: lbsn,
	}
	lb := grpc.NewServer(grpc.Creds(lbCreds))
	if err != nil {
		t.Fatalf("Failed to generate the port number %v", err)
	}
	be := &lbpb.Server{
		IpAddress:        []byte(beAddr[0]),
		Port:             int32(bePort),
		LoadBalanceToken: lbToken,
		DropRequest:      true,
	}
	var bes []*lbpb.Server
	bes = append(bes, be)
	sl := &lbpb.ServerList{
		Servers: bes,
	}
	ls := newRemoteBalancer(sl)
	lbpb.RegisterLoadBalancerServer(lb, ls)
	go func() {
		lb.Serve(lbLis)
	}()
	defer func() {
		ls.stop()
		lb.Stop()
	}()
	creds := serverNameCheckCreds{
		expected: besn,
	}
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	cc, err := grpc.DialContext(ctx, besn, grpc.WithBalancer(Balancer(&testNameResolver{
		addr: lbLis.Addr().String(),
	})), grpc.WithBlock(), grpc.WithTransportCredentials(&creds))
	if err != nil {
		t.Fatalf("Failed to dial to the backend %v", err)
	}
	helloC := hwpb.NewGreeterClient(cc)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Millisecond)
	if _, err := helloC.SayHello(ctx, &hwpb.HelloRequest{Name: "grpc"}, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded {
		t.Fatalf("%v.SayHello(_, _) = _, %v, want _, %s", helloC, err, codes.DeadlineExceeded)
	}
	cc.Close()
}
コード例 #13
0
ファイル: application.go プロジェクト: h2object/h2forward
func (app *Application) Init() error {
	httpAddr, err := net.ResolveTCPAddr("tcp", app.Options.HTTPAddress)
	if err != nil {
		return err
	}
	app.httpAddr = httpAddr

	httpListener, err := net.Listen("tcp", app.httpAddr.String())
	if err != nil {
		return err
	}
	app.httpListener = httpListener

	apiAddr, err := net.ResolveTCPAddr("tcp", app.Options.APIAddress)
	if err != nil {
		return err
	}
	app.apiAddr = apiAddr

	apiListener, err := net.Listen("tcp", app.apiAddr.String())
	if err != nil {
		return err
	}
	app.apiListener = apiListener

	vhosts := NewVirtualHost(app.Options.Root, app.Logger)
	if err := vhosts.Load(); err != nil {
		return err
	}
	app.vhosts = vhosts

	forwarder, err := forward.New(forward.Logger(app.Logger))
	if err != nil {
		return err
	}
	app.forwarder = forwarder

	reverser, err := reverse.New(app.forwarder, reverse.Route(app.vhosts), reverse.Logger(app.Logger))
	if err != nil {
		return err
	}
	app.reverser = reverser

	app.api = NewAPIController(app.vhosts)
	appid_dft, _ := util.AlphaStringRange(24, 32)
	secret_dft, _ := util.AlphaStringRange(32, 36)

	app.Configs.SetSection("forward")
	appid := app.Configs.StringDefault("appid", appid_dft)
	secret := app.Configs.StringDefault("secret", secret_dft)
	acl := app.Configs.BoolDefault("acl.enable", true)
	signature := app.api.sign(secret, appid)
	app.Info("application signature (%s)", signature)
	app.api.acl(acl)

	if err := app.Configs.Save(""); err != nil {
		return err
	}
	return nil
}
コード例 #14
0
ファイル: lookup.go プロジェクト: jash16/download
func (l *LookupServer) Main() {
	l.logf("lookup server start")

	tcpListener, err := net.Listen("tcp", l.Opts.TcpAddress)
	if err != nil {
		l.logf("error, Listen(%s) failed - %s", l.Opts.TcpAddress, err)
		os.Exit(1)
	}
	l.Lock()
	l.tcpListener = tcpListener
	l.Unlock()

	ctx := &context{s: l}
	tcpSrv := &tcpServer{ctx: ctx}
	l.wg.Wrap(func() {
		proto.TCPServer(l.tcpListener, tcpSrv, l.Opts.Logger)
	})

	httpListener, err := net.Listen("tcp", l.Opts.HttpAddress)
	if err != nil {
		l.logf("error, Listen(%s) failed - %s", l.Opts.HttpAddress, err)
		os.Exit(1)
	}
	l.Lock()
	l.httpListener = httpListener
	l.Unlock()
	hServer := &httpServer{ctx: ctx}
	l.wg.Wrap(func() {
		http_wrap.ServeHttp(l.httpListener, hServer, l.Opts.Logger)
	})

}
コード例 #15
0
ファイル: server.go プロジェクト: dgodd/caddy
// ListenAndServe starts the server with a new listener. It blocks until the server stops.
func (s *Server) ListenAndServe() error {
	err := s.setup()
	if err != nil {
		defer close(s.startChan)
		return err
	}

	ln, err := net.Listen("tcp", s.Addr)
	if err != nil {
		var succeeded bool
		if runtime.GOOS == "windows" { // TODO: Limit this to Windows only? (it keeps sockets open after closing listeners)
			for i := 0; i < 20; i++ {
				time.Sleep(100 * time.Millisecond)
				ln, err = net.Listen("tcp", s.Addr)
				if err == nil {
					succeeded = true
					break
				}
			}
		}
		if !succeeded {
			defer close(s.startChan)
			return err
		}
	}

	return s.serve(ln.(*net.TCPListener))
}
コード例 #16
0
ファイル: socket_test.go プロジェクト: jimjh/octopi
// TestRedirects ensures that the socket follows redirects, if they are given.
func TestRedirects(tester *testing.T) {

	t := test.New(tester)
	count1 := 0
	count2 := 0

	listener1, err := net.Listen("tcp", ":11111")
	t.AssertNil(err, "net.Listen")

	listener2, err := net.Listen("tcp", ":11112")
	t.AssertNil(err, "net.Listen")

	server1 := &http.Server{Handler: websocket.Handler(redirect(&count1))}
	server2 := &http.Server{Handler: websocket.Handler(accept(&count2))}

	go server1.Serve(listener1)
	go server2.Serve(listener2)

	socket := &Socket{
		HostPort: "localhost:11111",
		Path:     "",
		Origin:   "localhost:12345",
	}
	_, err = socket.Send(nil, 3, fakeOrigin)
	t.AssertNil(err, "socket.Send")

	listener1.Close()
	listener2.Close()

	matcher := new(test.IntMatcher)
	t.AssertEqual(matcher, 1, count1)
	t.AssertEqual(matcher, 1, count2)

}
コード例 #17
0
ファイル: app.go プロジェクト: nodephp/ledisdb
func NewApp(cfg *Config) (*App, error) {
	app := new(App)

	app.closed = false

	app.cfg = cfg

	var err error

	if strings.Contains(cfg.Addr, "/") {
		app.listener, err = net.Listen("unix", cfg.Addr)
	} else {
		app.listener, err = net.Listen("tcp", cfg.Addr)
	}

	if err != nil {
		return nil, err
	}

	app.db, err = leveldb.OpenWithConfig(&cfg.DB)
	if err != nil {
		return nil, err
	}

	app.kvTx = app.newTx()
	app.listTx = app.newTx()
	app.hashTx = app.newTx()
	app.zsetTx = app.newTx()

	return app, nil
}
コード例 #18
0
ファイル: nsqlookupd.go プロジェクト: CliffYuan/nsq
func (l *NSQLookupd) Main() {
	ctx := &Context{l}

	tcpListener, err := net.Listen("tcp", l.opts.TCPAddress)
	if err != nil {
		l.logf("FATAL: listen (%s) failed - %s", l.opts.TCPAddress, err)
		os.Exit(1)
	}
	l.Lock()
	l.tcpListener = tcpListener
	l.Unlock()
	tcpServer := &tcpServer{ctx: ctx}
	l.waitGroup.Wrap(func() {
		protocol.TCPServer(tcpListener, tcpServer, l.opts.Logger)
	})

	httpListener, err := net.Listen("tcp", l.opts.HTTPAddress)
	if err != nil {
		l.logf("FATAL: listen (%s) failed - %s", l.opts.HTTPAddress, err)
		os.Exit(1)
	}
	l.Lock()
	l.httpListener = httpListener
	l.Unlock()
	httpServer := newHTTPServer(ctx)
	l.waitGroup.Wrap(func() {
		http_api.Serve(httpListener, httpServer, "HTTP", l.opts.Logger)
	})
}
コード例 #19
0
ファイル: server.go プロジェクト: ably-forks/flynn
func (s *Server) Start() error {
	var err error
	sl, err := net.Listen("tcp", s.conf.SyslogAddr)
	if err != nil {
		return err
	}
	s.syslogListener = keepalive.Listener(sl)

	al, err := net.Listen("tcp", s.conf.ApiAddr)
	if err != nil {
		return err
	}
	s.apiListener = keepalive.Listener(al)

	if s.conf.Discoverd != nil {
		s.hb, err = s.conf.Discoverd.AddServiceAndRegister(s.conf.ServiceName, s.conf.SyslogAddr)
		if err != nil {
			return err
		}
	}

	go s.runSyslog()
	go http.Serve(s.apiListener, s.api)

	return nil
}
コード例 #20
0
ファイル: rpcserver.go プロジェクト: kazcw/btcd
// newRPCServer returns a new instance of the rpcServer struct.
func newRPCServer(s *server) (*rpcServer, error) {
	rpc := rpcServer{
		server: s,
	}
	// Get values from config
	rpc.rpcport = cfg.RPCPort
	rpc.username = cfg.RPCUser
	rpc.password = cfg.RPCPass

	// IPv4 listener.
	var listeners []net.Listener
	listenAddr4 := net.JoinHostPort("127.0.0.1", rpc.rpcport)
	listener4, err := net.Listen("tcp4", listenAddr4)
	if err != nil {
		log.Errorf("[RPCS] Couldn't create listener: %v", err)
		return nil, err
	}
	listeners = append(listeners, listener4)

	// IPv6 listener.
	listenAddr6 := net.JoinHostPort("::1", rpc.rpcport)
	listener6, err := net.Listen("tcp6", listenAddr6)
	if err != nil {
		log.Errorf("[RPCS] Couldn't create listener: %v", err)
		return nil, err
	}
	listeners = append(listeners, listener6)

	rpc.listeners = listeners
	return &rpc, err
}
コード例 #21
0
ファイル: app.go プロジェクト: Neeke/beego
func (app *App) Run() {
	addr := HttpAddr

	if HttpPort != 0 {
		addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort)
	}

	BeeLogger.Info("Running on %s", addr)

	var (
		err error
		l   net.Listener
	)

	if UseFcgi {
		if HttpPort == 0 {
			l, err = net.Listen("unix", addr)
		} else {
			l, err = net.Listen("tcp", addr)
		}
		if err != nil {
			BeeLogger.Critical("Listen: ", err)
		}
		err = fcgi.Serve(l, app.Handlers)
	} else {
		if EnableHotUpdate {
			server := &http.Server{
				Handler:      app.Handlers,
				ReadTimeout:  time.Duration(HttpServerTimeOut) * time.Second,
				WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
			}
			laddr, err := net.ResolveTCPAddr("tcp", addr)
			if nil != err {
				BeeLogger.Critical("ResolveTCPAddr:", err)
			}
			l, err = GetInitListner(laddr)
			theStoppable = newStoppable(l)
			err = server.Serve(theStoppable)
			theStoppable.wg.Wait()
			CloseSelf()
		} else {
			s := &http.Server{
				Addr:         addr,
				Handler:      app.Handlers,
				ReadTimeout:  time.Duration(HttpServerTimeOut) * time.Second,
				WriteTimeout: time.Duration(HttpServerTimeOut) * time.Second,
			}
			if HttpTLS {
				err = s.ListenAndServeTLS(HttpCertFile, HttpKeyFile)
			} else {
				err = s.ListenAndServe()
			}
		}
	}

	if err != nil {
		BeeLogger.Critical("ListenAndServe: ", err)
		time.Sleep(100 * time.Microsecond)
	}
}
コード例 #22
0
ファイル: nsqlookupd.go プロジェクト: RetVal/nsq
func (l *NSQLookupd) Main() {
	ctx := &Context{l}

	tcpListener, err := net.Listen("tcp", l.tcpAddr.String())
	if err != nil {
		l.logf("FATAL: listen (%s) failed - %s", l.tcpAddr, err)
		os.Exit(1)
	}
	l.tcpListener = tcpListener
	tcpServer := &tcpServer{ctx: ctx}
	l.waitGroup.Wrap(func() {
		util.TCPServer(tcpListener, tcpServer, l.opts.Logger)
	})

	httpListener, err := net.Listen("tcp", l.httpAddr.String())
	if err != nil {
		l.logf("FATAL: listen (%s) failed - %s", l.httpAddr, err)
		os.Exit(1)
	}
	l.httpListener = httpListener
	httpServer := &httpServer{ctx: ctx}
	l.waitGroup.Wrap(func() {
		util.HTTPServer(httpListener, httpServer, l.opts.Logger, "HTTP")
	})
}
コード例 #23
0
// This is just a test that shows how to instantiate a gossip component
func TestNewGossipCryptoService(t *testing.T) {
	s1 := grpc.NewServer()
	s2 := grpc.NewServer()
	s3 := grpc.NewServer()

	ll1, _ := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 5611))
	ll2, _ := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 5612))
	ll3, _ := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 5613))

	endpoint1 := "localhost:5611"
	endpoint2 := "localhost:5612"
	endpoint3 := "localhost:5613"

	g1 := NewGossipComponent(endpoint1, s1, []grpc.DialOption{grpc.WithInsecure()})
	g2 := NewGossipComponent(endpoint2, s2, []grpc.DialOption{grpc.WithInsecure()}, endpoint1)
	g3 := NewGossipComponent(endpoint3, s3, []grpc.DialOption{grpc.WithInsecure()}, endpoint1)
	go s1.Serve(ll1)
	go s2.Serve(ll2)
	go s3.Serve(ll3)

	time.Sleep(time.Second * 5)
	fmt.Println(g1.GetPeers())
	fmt.Println(g2.GetPeers())
	fmt.Println(g3.GetPeers())
	time.Sleep(time.Second)
}
コード例 #24
0
ファイル: server.go プロジェクト: lucmichalski/taurus
func newListener(proto, addr string, tlsConfig *tls.Config) (net.Listener, error) {
	var (
		l   net.Listener
		err error
	)

	switch proto {
	case "unix", "unixpacket":
		// Unix sockets must be unlink()ed before being reused again
		if err := syscall.Unlink(addr); err != nil && !os.IsNotExist(err) {
			return nil, err
		}
		l, err = net.Listen(proto, addr)
	case "tcp":
		l, err = net.Listen(proto, addr)
	default:
		return nil, fmt.Errorf("unsupported protocol: %q", proto)
	}

	if tlsConfig != nil {
		tlsConfig.NextProtos = []string{"http/1.1"}
		l = tls.NewListener(l, tlsConfig)
	}

	return l, err
}
コード例 #25
0
ファイル: nsqd.go プロジェクト: hzrandd/nsq
func (n *NSQD) Main() {
	context := &context{n}

	n.waitGroup.Wrap(func() { n.lookupLoop() })

	tcpListener, err := net.Listen("tcp", n.tcpAddr.String())
	if err != nil {
		log.Fatalf("FATAL: listen (%s) failed - %s", n.tcpAddr, err.Error())
	}
	n.tcpListener = tcpListener
	tcpServer := &tcpServer{context: context}
	n.waitGroup.Wrap(func() { util.TCPServer(n.tcpListener, tcpServer) })

	httpListener, err := net.Listen("tcp", n.httpAddr.String())
	if err != nil {
		log.Fatalf("FATAL: listen (%s) failed - %s", n.httpAddr, err.Error())
	}
	n.httpListener = httpListener
	httpServer := &httpServer{context: context}
	n.waitGroup.Wrap(func() { util.HTTPServer(n.httpListener, httpServer) })

	if n.options.StatsdAddress != "" {
		n.waitGroup.Wrap(func() { n.statsdLoop() })
	}
}
コード例 #26
0
ファイル: gatekeeper.go プロジェクト: vaibhav2800/forge
func startWebserver() (err error) {
	server := http.Server{Handler: gateKeeperMux}
	if cmdline.tls {
		// copied from net.http ListenAndServeTLS()
		// so we have a reference to the Listener to close it on /quit/
		config := &tls.Config{}
		config.NextProtos = []string{"http/1.1"}
		config.Certificates = make([]tls.Certificate, 1)
		config.Certificates[0], err =
			tls.LoadX509KeyPair(cmdline.cert, cmdline.key)
		if err != nil {
			return
		}
		wsListener, err = net.Listen("tcp", cmdline.laddr)
		if err != nil {
			return
		}
		wsListener = tls.NewListener(wsListener, config)
	} else {
		wsListener, err = net.Listen("tcp", cmdline.laddr)
		if err != nil {
			return
		}
	}

	startCookieServer()
	err = server.Serve(wsListener)
	stopCookieServer()

	fmt.Println("Shutting down in", cmdline.quittimeout, "second(s)...")
	time.Sleep(time.Duration(cmdline.quittimeout) * time.Second)

	return err
}
コード例 #27
0
ファイル: Connector_test.go プロジェクト: Griesbacher/nagflux
func (mockLive *MockLivestatus) StartMockLivestatus() {
	var listener net.Listener
	var err error
	switch mockLive.ConnectionType {
	case "tcp":
		listener, err = net.Listen("tcp", mockLive.LivestatusAddress)
	case "file":
		listener, err = net.Listen("unix", mockLive.LivestatusAddress)
	default:
		log.Panic("ConnectionType undefined")
		return
	}

	if err != nil {
		log.Panic(err)
	}

	isRunning := true
	for isRunning {
		conn, err := listener.Accept()
		if err != nil {
			//log.Println(err)
			continue
		}
		go mockLive.handle(conn)

		mutex.Lock()
		isRunning = mockLive.isRunning
		mutex.Unlock()
	}
}
コード例 #28
0
ファイル: server.go プロジェクト: vmware/vic
func (s *server) listen() error {
	defer trace.End(trace.Begin(""))

	var err error
	s.uss = NewUserSessionStore()
	certificate, err := vchConfig.HostCertificate.Certificate()
	if err != nil {
		log.Errorf("Could not load certificate from config - running without TLS: %s", err)

		s.l, err = net.Listen("tcp", s.addr)
		return err
	}

	// FIXME: assignment copies lock value to tlsConfig: crypto/tls.Config contains sync.Once contains sync.Mutex
	tlsconfig := func(c *tls.Config) *tls.Config {
		// if there are CAs, then TLS is enabled
		if len(vchConfig.CertificateAuthorities) != 0 {
			if c.ClientCAs == nil {
				c.ClientCAs = x509.NewCertPool()
			}
			if !c.ClientCAs.AppendCertsFromPEM(vchConfig.CertificateAuthorities) {
				log.Errorf("Unable to load CAs from config; client auth via certificate will not function")
			}
			c.ClientAuth = tls.VerifyClientCertIfGiven
		} else {
			log.Warnf("No certificate authorities found for certificate-based authentication. This may be intentional, however, authentication is disabled")
		}

		return &tls.Config{
			Certificates:             c.Certificates,
			NameToCertificate:        c.NameToCertificate,
			GetCertificate:           c.GetCertificate,
			RootCAs:                  c.RootCAs,
			NextProtos:               c.NextProtos,
			ServerName:               c.ServerName,
			ClientAuth:               c.ClientAuth,
			ClientCAs:                c.ClientCAs,
			InsecureSkipVerify:       c.InsecureSkipVerify,
			CipherSuites:             c.CipherSuites,
			PreferServerCipherSuites: c.PreferServerCipherSuites,
			SessionTicketsDisabled:   c.SessionTicketsDisabled,
			SessionTicketKey:         c.SessionTicketKey,
			ClientSessionCache:       c.ClientSessionCache,
			MinVersion:               tls.VersionTLS12,
			MaxVersion:               c.MaxVersion,
			CurvePreferences:         c.CurvePreferences,
		}
	}(&tlsconfig.ServerDefault)

	tlsconfig.Certificates = []tls.Certificate{*certificate}

	innerListener, err := net.Listen("tcp", s.addr)
	if err != nil {
		log.Fatal(err)
		return err
	}

	s.l = tls.NewListener(innerListener, tlsconfig)
	return nil
}
コード例 #29
0
ファイル: server.go プロジェクト: anywhy/tidb
// NewServer creates a new Server.
func NewServer(cfg *Config, driver IDriver) (*Server, error) {
	s := &Server{
		cfg:               cfg,
		driver:            driver,
		concurrentLimiter: NewTokenLimiter(100),
		rwlock:            &sync.RWMutex{},
		clients:           make(map[uint32]*clientConn),
	}

	var err error
	if cfg.Socket != "" {
		cfg.SkipAuth = true
		s.listener, err = net.Listen("unix", cfg.Socket)
	} else {
		s.listener, err = net.Listen("tcp", s.cfg.Addr)
	}
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Init rand seed for randomBuf()
	rand.Seed(time.Now().UTC().UnixNano())
	log.Infof("Server run MySql Protocol Listen at [%s]", s.cfg.Addr)
	return s, nil
}
コード例 #30
0
ファイル: server.go プロジェクト: rlmcpherson/followermaze-go
// Start starts a followermaze server listening for events at srcAddr and clients at clientAddr
// firstSequenceID must be set to the first event id to expect (usually 1)
func Start(srcAddr, clientAddr string, firstSequenceID int) (*Server, error) {

	done := make(chan struct{}) // used to stop server goroutines

	// start notifier
	ech, connch, err := notifier(firstSequenceID, done)
	if err != nil {
		return nil, err
	}

	// start src, client servers
	srcSrv, err := net.Listen("tcp", srcAddr)
	if err != nil {
		return nil, err
	}
	clientSrv, err := net.Listen("tcp", clientAddr)
	if err != nil {
		return nil, err
	}

	// pass the servers and connHandler functions to runListener
	go runListener(clientSrv, clientHandler(connch), done)
	go runListener(srcSrv, srcHandler(ech), done)
	return &Server{done, true, srcSrv, clientSrv}, nil
}