本文整理汇总了Golang中net.Listen函数的典型用法代码示例。如果您正苦于以下问题:Golang Listen函数的具体用法?Golang Listen怎么用?Golang Listen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Listen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: run
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: getFreePort
// 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: listenAndServeScgi
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: listenTo
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, "[email protected]") {
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, "[email protected]") {
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: TestReconnect
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: Listen
// 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: Init
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: NewAppWithConfig
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: newServer
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: TestTCP
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: main
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: TestDropRequestFailedNonFailFast
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: Init
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: Main
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: ListenAndServe
// 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))
}