本文整理汇总了Golang中net.TCPListener类的典型用法代码示例。如果您正苦于以下问题:Golang TCPListener类的具体用法?Golang TCPListener怎么用?Golang TCPListener使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TCPListener类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Relaunch
// Re-exec this image without dropping the listener passed to this function.
func Relaunch(l *net.TCPListener) error {
f, err := l.File()
if nil != err {
return err
}
argv0, err := exec.LookPath(os.Args[0])
if nil != err {
return err
}
wd, err := os.Getwd()
if nil != err {
return err
}
err = os.Setenv("GOAGAIN_FD", fmt.Sprint(f.Fd()))
if nil != err {
return err
}
err = os.Setenv("GOAGAIN_PPID", strconv.Itoa(syscall.Getpid()))
if nil != err {
return err
}
p, err := os.StartProcess(argv0, os.Args, &os.ProcAttr{
Dir: wd,
Env: os.Environ(),
Files: []*os.File{os.Stdin, os.Stdout, os.Stderr, f},
Sys: &syscall.SysProcAttr{},
})
if nil != err {
return err
}
log.Printf("spawned child %d\n", p.Pid)
return nil
}
示例2: newServer
func newServer(s *state.State, lis *net.TCPListener, cfg ServerConfig) (_ *Server, err error) {
logger.Infof("listening on %q", lis.Addr())
srv := &Server{
state: s,
statePool: state.NewStatePool(s),
addr: lis.Addr().(*net.TCPAddr), // cannot fail
tag: cfg.Tag,
dataDir: cfg.DataDir,
logDir: cfg.LogDir,
limiter: utils.NewLimiter(loginRateLimit),
validator: cfg.Validator,
adminApiFactories: map[int]adminApiFactory{
0: newAdminApiV0,
1: newAdminApiV1,
2: newAdminApiV2,
},
}
srv.authCtxt = newAuthContext(srv)
tlsCert, err := tls.X509KeyPair(cfg.Cert, cfg.Key)
if err != nil {
return nil, err
}
// TODO(rog) check that *srvRoot is a valid type for using
// as an RPC server.
tlsConfig := tls.Config{
Certificates: []tls.Certificate{tlsCert},
}
changeCertListener := newChangeCertListener(lis, cfg.CertChanged, tlsConfig)
go srv.run(changeCertListener)
return srv, nil
}
示例3: serveTCP
// serveTCP starts a TCP listener for the server.
// Each request is handled in a separate goroutine.
func (srv *Server) serveTCP(l *net.TCPListener) error {
defer l.Close()
if srv.NotifyStartedFunc != nil {
srv.NotifyStartedFunc()
}
handler := srv.Handler
if handler == nil {
handler = DefaultServeMux
}
rtimeout := srv.getReadTimeout()
// deadline is not used here
for {
rw, e := l.AcceptTCP()
if e != nil {
continue
}
m, e := srv.readTCP(rw, rtimeout)
select {
case <-srv.stopTCP:
return nil
default:
}
if e != nil {
continue
}
srv.wgTCP.Add(1)
go srv.serve(rw.RemoteAddr(), handler, m, nil, nil, rw)
}
panic("dns: not reached")
}
示例4: Start
func (this *Server) Start(listener *net.TCPListener) {
log.Printf("Start listen on %v", listener.Addr())
this.waitGroup.Add(1)
defer func() {
listener.Close()
this.waitGroup.Done()
}()
for {
select {
case <-this.exitCh:
log.Printf("Stop listen on %v", listener.Addr())
return
default:
}
listener.SetDeadline(time.Now().Add(this.acceptTimeout))
conn, err := listener.AcceptTCP()
if err != nil {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
// log.Printf("Accept timeout: %v", opErr)
continue
}
log.Printf("Accept error: %v", err)
continue
}
log.Printf("Accept: %v", conn.RemoteAddr())
go this.handleClientConn(conn)
}
}
示例5: Server
func Server(listen *net.TCPListener) {
for {
conn, err := listen.AcceptTCP()
if err != nil {
log.Printf("接受客户端连接异常:%v", err)
continue
}
log.Printf("客户端来自:%s", conn.RemoteAddr().String())
defer conn.Close()
go func() {
data := make([]byte, 2)
fmt.Printf("data len:%v\n", len(data))
for {
// i,err := conn.Read(data)
i, err := io.ReadFull(conn, data)
fmt.Printf("data len:%v\n", len(data))
log.Printf("客户端%s.发来数据:%s", conn.RemoteAddr().String(), string(data[0:i]))
if err != nil {
log.Printf("读取客户端数据错误:%v", err)
break
}
conn.Write([]byte{'f', 'i', 'n', 's', 'h'})
}
}()
}
}
示例6: acceptConnection
func (server *GoTelnet) acceptConnection(listener *net.TCPListener) {
conn, _ := listener.Accept()
server.chanForNextAccept <- true
if server.preConnection != nil {
(*server.preConnection).Close()
}
server.preConnection = &conn
conn.Write([]byte("welcome to telnet debug server"))
defer conn.Close()
for {
buf := make([]byte, 1024)
readlen, ok := conn.Read(buf)
if ok != nil {
fmt.Fprintf(os.Stderr, "close connection when reading from socket: %s\n", ok.String())
return
}
if readlen == 0 {
fmt.Printf("Connection closed by remote host\n")
return
}
if buf[0] == 13 {
conn.Write([]byte(server.Promote + ">"))
}
if string(buf[0:3]) == "bye" {
conn.Write(buf)
break
}
server.commandHandler.Handle(string(buf))
}
}
示例7: listenTcp
/**
* Listens for new public tcp connections from the internet.
*/
func (t *Tunnel) listenTcp(listener *net.TCPListener) {
for {
defer func() {
if r := recover(); r != nil {
log.Warn("listenTcp failed with error %v", r)
}
}()
// accept public connections
tcpConn, err := listener.AcceptTCP()
if err != nil {
// not an error, we're shutting down this tunnel
if atomic.LoadInt32(&t.closing) == 1 {
return
}
t.Error("Failed to accept new TCP connection: %v", err)
continue
}
conn := conn.Wrap(tcpConn, "pub")
conn.AddLogPrefix(t.Id())
conn.Info("New connection from %v", conn.RemoteAddr())
go t.HandlePublicConnection(conn)
}
}
示例8: serve
// serve accepts connections from the given TCP listener and dispatches each
// connection to the RPC server. Connections are only accepted from localhost
// and the seesaw node that we are configured to peer with.
func (s *syncServer) serve(l *net.TCPListener) error {
defer l.Close()
s.server = rpc.NewServer()
s.server.Register(&SeesawSync{s})
for {
c, err := l.AcceptTCP()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
time.Sleep(100 * time.Millisecond)
continue
}
return err
}
raddr := c.RemoteAddr().String()
host, _, err := net.SplitHostPort(raddr)
if err != nil {
log.Errorf("Failed to parse remote address %q: %v", raddr, err)
c.Close()
continue
}
rip := net.ParseIP(host)
if rip == nil || (!rip.IsLoopback() && !rip.Equal(s.engine.config.Peer.IPv4Addr) && !rip.Equal(s.engine.config.Peer.IPv6Addr)) {
log.Warningf("Rejecting connection from non-peer (%s)...", rip)
c.Close()
continue
}
log.Infof("Sync connection established from %s", rip)
go s.server.ServeConn(c)
}
}
示例9: startLocalProxyServer
func startLocalProxyServer(proxy ProxyConfig) (*net.TCPListener, error) {
tcpaddr, err := net.ResolveTCPAddr("tcp", proxy.Local)
if nil != err {
log.Fatalf("[ERROR]Local server address:%s error:%v", proxy.Local, err)
return nil, err
}
var lp *net.TCPListener
lp, err = net.ListenTCP("tcp", tcpaddr)
if nil != err {
log.Fatalf("Can NOT listen on address:%s", proxy.Local)
return nil, err
}
log.Printf("Listen on address %s", proxy.Local)
go func() {
for proxyServerRunning {
conn, err := lp.AcceptTCP()
if nil != err {
continue
}
go serveProxyConn(conn, proxy)
}
lp.Close()
}()
return lp, nil
}
示例10: startServer
func (ctx *bootContext) startServer() {
defer func() {
sigChan <- Bye
}()
var (
conn *net.TCPConn
ln *net.TCPListener
err error
)
server := NewServer(ctx.cman)
addr := ctx.cman.ListenAddr(SR_SERVER)
ln, err = net.ListenTCP("tcp", addr)
fatalError(err)
defer ln.Close()
ctx.register(server, ln)
log.Infoln(versionString())
log.Infoln("Server is listening on", addr)
for {
conn, err = ln.AcceptTCP()
if err == nil {
go server.TunnelServe(conn)
} else {
SafeClose(conn)
}
}
}
示例11: FreePorts
// FreePorts returns maximum n tcp ports available to use.
func FreePorts(n int, matchFunc func(int) bool) (ports []int, err error) {
if n > 50000 {
return nil, fmt.Errorf("too many ports requested (%d)", n)
}
for len(ports) < n {
var addr *net.TCPAddr
addr, err = net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
break
}
var l *net.TCPListener
l, err = net.ListenTCP("tcp", addr)
if err != nil {
break
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()
if matchFunc == nil {
ports = append(ports, port)
continue
}
if matchFunc(port) {
ports = append(ports, port)
}
}
return
}
示例12: startClient
func (ctx *bootContext) startClient() {
defer func() {
sigChan <- Bye
}()
var (
conn *net.TCPConn
ln *net.TCPListener
err error
)
client := NewClient(ctx.cman)
addr := ctx.cman.ListenAddr(SR_CLIENT)
ln, err = net.ListenTCP("tcp", addr)
fatalError(err)
defer ln.Close()
ctx.register(client, ln)
log.Infoln(versionString())
log.Infoln("Proxy(SOCKS5/HTTP) is listening on", addr)
// connect to server
go client.StartTun(true)
for {
conn, err = ln.AcceptTCP()
if err == nil {
go client.ClientServe(conn)
} else {
SafeClose(conn)
}
}
}
示例13: acceptConnections
// Accepts TCP connections on listener and sends them on the channel tcp_connections.
func acceptConnections(listener *net.TCPListener, tcp_connections chan<- *net.TCPConn) {
for {
message := true
for { // if we've reached the maximum number of connections, wait
if atomic.AddInt32(&ActiveConnections, 1) <= config.MaxConnections {
break
}
atomic.AddInt32(&ActiveConnections, -1)
if message {
util.Log(0, "WARNING! Maximum number of %v active connections reached => Throttling", config.MaxConnections)
message = false
}
time.Sleep(100 * time.Millisecond)
}
tcpConn, err := listener.AcceptTCP()
if err != nil {
if Shutdown {
return
}
util.Log(0, "ERROR! AcceptTCP: %v", err)
} else {
tcp_connections <- tcpConn
}
}
}
示例14: Server
func Server(listen *net.TCPListener) {
for {
conn, err := listen.AcceptTCP()
if err != nil {
fmt.Println("接受客户端连接异常:", err.Error())
continue
}
fmt.Println("客户端连接来自:", conn.RemoteAddr().String())
defer conn.Close()
go func() {
data := make([]byte, 128)
for {
i, err := conn.Read(data)
fmt.Println("客户端", conn.RemoteAddr().String(), "发来数据:", string(data[0:i]))
if err != nil {
fmt.Println("读取客户端数据错误:", err.Error())
break
}
sms := make([]byte, 128)
fmt.Print("请输入要发送的消息:")
fmt.Scan(&sms)
conn.Write(sms)
}
}()
}
}
示例15: fakeReadingAMI
func fakeReadingAMI(t *testing.T, l *net.TCPListener, expect [][]byte) {
lconn, err := l.Accept()
if err != nil {
t.Fail()
t.Log("error accepting", err)
return
}
err = lconn.SetDeadline(time.Now().Add(5 * time.Second))
//TODO
_, err = lconn.Write([]byte("Asterisk Call Manager/1.3\r\n"))
if err != nil {
t.Fail()
t.Log("error writing", err)
return
}
for _, a := range expect {
b := make([]byte, 1024)
n, err := lconn.Read(b)
if err != nil {
t.Fail()
t.Log("error reading:", err)
}
b = b[:n]
if !bytes.Equal(a, b) {
t.Fail()
t.Logf("read expected %#v, got %#v", string(a), string(b))
}
}
}