本文整理汇总了Golang中net.Listener.Addr方法的典型用法代码示例。如果您正苦于以下问题:Golang Listener.Addr方法的具体用法?Golang Listener.Addr怎么用?Golang Listener.Addr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.Listener
的用法示例。
在下文中一共展示了Listener.Addr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: hostPort
func (self *Serv) hostPort(ln net.Listener) (host string, port int) {
addr := ln.Addr().(*net.TCPAddr)
if host = self.hostname; len(host) == 0 {
host = addr.IP.String()
}
return host, addr.Port
}
示例2: Start
// Start instructs the TCPCollector to bind to the interface and accept connections.
func (s *TCPCollector) Start(c chan<- *Event) error {
var ln net.Listener
var err error
if s.tlsConfig == nil {
ln, err = net.Listen("tcp", s.iface)
} else {
ln, err = tls.Listen("tcp", s.iface, s.tlsConfig)
}
s.addr = ln.Addr()
if err != nil {
return err
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
continue
}
go s.handleConnection(conn, c)
}
}()
return nil
}
示例3: Serve
// Serve sets up the handler to serve requests on the passed in listener
func (h Handler) Serve(l net.Listener) error {
server := http.Server{
Addr: l.Addr().String(),
Handler: h.mux,
}
return server.Serve(l)
}
示例4: Relaunch
// Re-exec this image without dropping the listener passed to this function.
func Relaunch(l net.Listener) error {
argv0, err := exec.LookPath(os.Args[0])
if nil != err {
return err
}
wd, err := os.Getwd()
if nil != err {
return err
}
v := reflect.ValueOf(l).Elem().FieldByName("fd").Elem()
fd := uintptr(v.FieldByName("sysfd").Int())
noCloseOnExec(fd)
if err := os.Setenv("GOAGAIN_FD", fmt.Sprint(fd)); nil != err {
return err
}
if err := os.Setenv("GOAGAIN_NAME", fmt.Sprintf("tcp:%s->", l.Addr().String())); nil != err {
return err
}
files := make([]*os.File, fd+1)
files[syscall.Stdin] = os.Stdin
files[syscall.Stdout] = os.Stdout
files[syscall.Stderr] = os.Stderr
files[fd] = os.NewFile(fd, string(v.FieldByName("sysfile").String()))
p, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
Dir: wd,
Env: os.Environ(),
Files: files,
Sys: &syscall.SysProcAttr{},
})
if nil != err {
return err
}
log.Printf("spawned child %d\n", p.Pid)
return nil
}
示例5: forwardLocalConnectionsTo
// Forwards the local server listener to the specified target address (format host:port) using the SSH connection as tunnel.
// What this method does is the same as "ssh -L $ANY-PORT:jenkins-host:$TARGET-PORT" jenkins-host.
func (self *SSHTunnelEstablisher) forwardLocalConnectionsTo(config *util.Config, ssh *ssh.Client, listener net.Listener, targetAddress string) {
transfer := func(source io.ReadCloser, target io.Writer) {
defer source.Close()
_, _ = io.Copy(target, source)
}
establishBIDITransport := func(source net.Conn, target net.Conn) {
go transfer(source, target)
go transfer(target, source)
}
sshAddress := ssh.Conn.RemoteAddr().String()
localAddress := listener.Addr().String()
util.GOut("ssh-tunnel", "Forwarding local connections on '%v' to '%v' via '%v'.", localAddress, targetAddress, sshAddress)
for {
if sourceConnection, err := listener.Accept(); err == nil {
if targetConnection, err := ssh.Dial("tcp", targetAddress); err == nil {
establishBIDITransport(sourceConnection, targetConnection)
} else {
util.GOut("ssh-tunnel", "ERROR: Failed forwarding incoming local connection on '%v' to '%v' via '%v'.", localAddress, targetAddress, sshAddress)
}
} else {
util.GOut("ssh-tunnel", "Stop forwarding local connections on '%v' to '%v'.", localAddress, targetAddress)
return
}
}
}
示例6: Serve
// Serve accepts incoming connections on the listener lis, creating a new
// ServerTransport and service goroutine for each. The service goroutines
// read gRPC requests and then call the registered handlers to reply to them.
// Service returns when lis.Accept fails.
func (s *Server) Serve(lis net.Listener) error {
s.mu.Lock()
s.printf("serving")
if s.lis == nil {
s.mu.Unlock()
return ErrServerStopped
}
s.lis[lis] = true
s.mu.Unlock()
defer func() {
lis.Close()
s.mu.Lock()
delete(s.lis, lis)
s.mu.Unlock()
}()
listenerAddr := lis.Addr()
for {
rawConn, err := lis.Accept()
if err != nil {
s.mu.Lock()
s.printf("done serving; Accept = %v", err)
s.mu.Unlock()
return err
}
// Start a new goroutine to deal with rawConn
// so we don't stall this Accept loop goroutine.
go s.handleRawConn(listenerAddr, rawConn)
}
}
示例7: httpServer
//httpServer 启动http服务器并监听
func (ser *Server) httpServer(l net.Listener) {
var (
addr = l.Addr().String()
err error
)
httpServer := &http.Server{
Addr: addr,
Handler: http.HandlerFunc(ser.httpHandler),
TLSConfig: ser.TLSConfig,
}
httpServer.SetKeepAlivesEnabled(true)
addrs := strings.Split(addr, ":")
if addrs[1] == "443" || addrs[1] == "https" {
tlsConfig := new(tls.Config)
if httpServer.TLSConfig != nil {
*tlsConfig = *httpServer.TLSConfig
}
if tlsConfig.NextProtos == nil {
tlsConfig.NextProtos = []string{"http/1.1"}
}
l = tls.NewListener(l, tlsConfig)
}
err = httpServer.Serve(l)
CheckErr("服务器停止", err)
}
示例8: listenForConnections
// Listens for connections on the given listener and puts them in the channel.
// Blocks while still receiving connections.
// Returns an error on network problem, or nil if shutdown requested
func listenForConnections(l net.Listener, c chan net.Conn) error {
id, shutdownRequested := shutdown.AddShutdownListener("Connection listener")
defer shutdown.RoutineDone(id)
log.WithFields(log.Fields{
"listening_on": fmt.Sprintf("%v", l.Addr()),
"fqdn": config.GetFQDN(),
}).Info("Starting connection listener")
// shutdown using the strategy found here http://stackoverflow.com/a/13419724
quit := false
go func() {
<-shutdownRequested
quit = true
l.Close()
}()
for {
conn, err := l.Accept()
if err != nil {
if quit {
log.Info("Shutting down connection listener")
return nil
}
l.Close()
return err
}
c <- conn
}
}
示例9: main
func main() {
// parse command line args
addr = flag.String("listen", ":9876", "Address that the server will listen on (passed as is to net.Listen)")
remoteaddr = flag.String("remoteaddr", "localhost", "IP or domain name of this server, to be used when generating links to items")
remoteport = flag.Int("remoteport", 9876, "Port that this server will be available on, to be used when generating links to items")
cache_time = flag.Int("cachetime", 1200, "Cached items' life span")
flag.Parse()
log.Println("Launching Gopher server...")
var ln net.Listener
var err error
// listen on specified address
ln, err = net.Listen("tcp", *addr)
if err != nil {
log.Fatalln(err) // an error occured, can't listen
}
log.Printf("Listening at %s", ln.Addr())
// loop forever
for {
var conn net.Conn
conn, err = ln.Accept()
if err != nil {
log.Println(err)
} else {
go HandleConnection(conn) // HandleConnection is defined in gopher.go
}
}
}
示例10: TestStateTransitionActiveIdleClosed
// Test state transitions from new->active->-idle->closed using an actual
// network connection and make sure the waitgroup count is correct at the end.
func TestStateTransitionActiveIdleClosed(t *testing.T) {
var (
listener net.Listener
exitchan chan error
)
keyFile, err1 := helpers.NewTempFile(helpers.Key)
certFile, err2 := helpers.NewTempFile(helpers.Cert)
defer keyFile.Unlink()
defer certFile.Unlink()
if err1 != nil || err2 != nil {
t.Fatal("Failed to create temporary files", err1, err2)
}
for _, withTLS := range []bool{false, true} {
server := NewServer()
wg := helpers.NewWaitGroup()
statechanged := make(chan http.ConnState)
server.wg = wg
if withTLS {
listener, exitchan = startTLSServer(t, server, certFile.Name(), keyFile.Name(), statechanged)
} else {
listener, exitchan = startServer(t, server, statechanged)
}
client := newClient(listener.Addr(), withTLS)
client.Run()
// wait for client to connect, but don't let it send the request
if err := <-client.connected; err != nil {
t.Fatal("Client failed to connect to server", err)
}
client.sendrequest <- true
waitForState(t, statechanged, http.StateActive, "Client failed to reach active state")
rr := <-client.response
if rr.err != nil {
t.Fatalf("tls=%t unexpected error from client %s", withTLS, rr.err)
}
waitForState(t, statechanged, http.StateIdle, "Client failed to reach idle state")
// client is now in an idle state
close(client.sendrequest)
<-client.closed
waitForState(t, statechanged, http.StateClosed, "Client failed to reach closed state")
server.Close()
waiting := <-wg.WaitCalled
if waiting != 0 {
t.Errorf("Waitcount should be zero, got %d", waiting)
}
if err := <-exitchan; err != nil {
t.Error("Unexpected error during shutdown", err)
}
}
}
示例11: handleListener
func handleListener(manager *connmgr.ConnManager, listener net.Listener, artemisServerAddr string) {
log.Printf("Proxy server started on %v", listener.Addr())
err := connmgr.ServeReverseProxy(manager, listener, artemisServerAddr)
// TODO: Use cfg.LogNewConnections.
log.Printf("Proxy server stopped on %v with error: %v", listener.Addr(), err)
}
示例12: newHTTPServer
func (s *server) newHTTPServer(
proto, laddr string, tlsConfig *tls.Config) (*HTTPServer, error) {
var (
l net.Listener
err error
)
if tlsConfig != nil {
l, err = tls.Listen(proto, laddr, tlsConfig)
} else {
l, err = net.Listen(proto, laddr)
}
if err != nil {
return nil, err
}
host := fmt.Sprintf("%s://%s", proto, laddr)
ctx := s.ctx.WithValue(context.HostKey, host)
ctx = ctx.WithValue(context.TLSKey, tlsConfig != nil)
logger := ctx.Value(context.LoggerKey).(*log.Logger)
errLogger := &httpServerErrLogger{logger}
srv := &http.Server{Addr: l.Addr().String()}
srv.ErrorLog = golog.New(errLogger, "", 0)
return &HTTPServer{
srv: srv,
l: l,
ctx: ctx,
}, nil
}
示例13: serve
func (srv *Server) serve(l net.Listener) error {
if ln, ok := l.(*net.TCPListener); ok {
srv.logf("powermux: using TCP keep-alive for %s", l.Addr())
l = tcpKeepAliveListener{ln}
}
return srv.server().Serve(l)
}
示例14: ListenAndServeHTTP
// ListenAndServe makes the client listen for HTTP connections at a the given
// address or, if a blank address is given, at a random port on localhost.
// onListeningFn is a callback that gets invoked as soon as the server is
// accepting TCP connections.
func (client *Client) ListenAndServeHTTP(requestedAddr string, onListeningFn func()) error {
log.Debug("About to listen")
if requestedAddr == "" {
requestedAddr = "localhost:0"
}
var err error
var l net.Listener
if l, err = net.Listen("tcp", requestedAddr); err != nil {
return fmt.Errorf("Unable to listen: %q", err)
}
client.l = l
listenAddr := l.Addr().String()
addr.Set(listenAddr)
onListeningFn()
httpServer := &http.Server{
ReadTimeout: client.ReadTimeout,
WriteTimeout: client.WriteTimeout,
Handler: client,
ErrorLog: log.AsStdLogger(),
}
log.Debugf("About to start HTTP client proxy at %v", listenAddr)
return httpServer.Serve(l)
}
示例15: listenAndServe
func (h *Handler) listenAndServe(proto, addr, group string) error {
server := http.Server{
Addr: addr,
Handler: h.mux,
}
start := make(chan struct{})
var l net.Listener
var err error
switch proto {
case "tcp":
l, err = newTCPSocket(addr, nil, start)
if err == nil {
err = writeSpec(group, l.Addr().String())
}
case "unix":
var s string
s, err = fullSocketAddr(addr)
if err == nil {
l, err = newUnixSocket(s, group, start)
}
}
if err != nil {
return err
}
close(start)
return server.Serve(l)
}