當前位置: 首頁>>代碼示例>>Golang>>正文


Golang TCPConn.SetKeepAlive方法代碼示例

本文整理匯總了Golang中net.TCPConn.SetKeepAlive方法的典型用法代碼示例。如果您正苦於以下問題:Golang TCPConn.SetKeepAlive方法的具體用法?Golang TCPConn.SetKeepAlive怎麽用?Golang TCPConn.SetKeepAlive使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net.TCPConn的用法示例。


在下文中一共展示了TCPConn.SetKeepAlive方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: startLink

func (h *Hub) startLink(l *link, conn *net.TCPConn) {
	conn.SetKeepAlive(true)
	conn.SetKeepAlivePeriod(time.Second * 60)
	l.setConn(conn)

	Info("link(%d) start: %v", l.id, conn.RemoteAddr())
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			data, err := l.read()
			if err != nil {
				if err != errPeerClosed {
					h.SendCmd(l.id, LINK_CLOSE_SEND)
				}
				break
			}

			h.Send(l.id, data)
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		err := l._write()
		if err != errPeerClosed {
			h.SendCmd(l.id, LINK_CLOSE_RECV)
		}
	}()
	wg.Wait()
	Info("link(%d) close", l.id)
}
開發者ID:yongshun,項目名稱:gotunnel,代碼行數:34,代碼來源:link.go

示例2: acceptTCP

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func acceptTCP(server *Server, lis *net.TCPListener) {
	var (
		conn *net.TCPConn
		err  error
		r    int
	)
	for {
		if conn, err = lis.AcceptTCP(); err != nil {
			// if listener close then return
			log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
			return
		}
		if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
			log.Error("conn.SetKeepAlive() error(%v)", err)
			return
		}
		if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
			log.Error("conn.SetReadBuffer() error(%v)", err)
			return
		}
		if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
			log.Error("conn.SetWriteBuffer() error(%v)", err)
			return
		}
		go serveTCP(server, conn, r)
		if r++; r == maxInt {
			r = 0
		}
	}
}
開發者ID:vincentqiu,項目名稱:goim,代碼行數:33,代碼來源:tcp.go

示例3: Start

func (server *TcpServer) Start() (err error) {
	for {
		var conn *net.TCPConn
		if conn, err = server.TCPListener.AcceptTCP(); err != nil {
			return err
		}
		if server.keepAlive != nil {
			if err := conn.SetKeepAlive(server.keepAlive.(bool)); err != nil {
				return err
			}
		}
		if server.keepAlivePeriod != nil {
			if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok {
				if err := kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil {
					return err
				}
			}
		}
		if server.linger != nil {
			if err := conn.SetLinger(server.linger.(int)); err != nil {
				return err
			}
		}
		if server.noDelay != nil {
			if err := conn.SetNoDelay(server.noDelay.(bool)); err != nil {
				return err
			}
		}
		if server.readBuffer != nil {
			if err := conn.SetReadBuffer(server.readBuffer.(int)); err != nil {
				return err
			}
		}
		if server.writerBuffer != nil {
			if err := conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil {
				return err
			}
		}
		if server.deadline != nil {
			if err := conn.SetDeadline(server.deadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.readDeadline != nil {
			if err := conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.writerDeadline != nil {
			if err := conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil {
				return err
			}
		}
		if server.config != nil {
			server.ServeTCP(tls.Client(conn, server.config))
		} else {
			server.ServeTCP(conn)
		}
	}
}
開發者ID:jueebushe,項目名稱:hprose-go,代碼行數:60,代碼來源:tcp_service.go

示例4: handleClient

func handleClient(pf *PF, source *net.TCPConn) {
	atomic.AddInt32(&pf.status.actives, 1)
	defer func() {
		atomic.AddInt32(&pf.status.actives, -1)
		pf.wg.Done()
	}()

	settings := pf.settings
	host := chooseHost(settings.weight, settings.Hosts)
	if host == nil {
		source.Close()
		logger.Println("choose host failed")
		return
	}

	dest, err := net.DialTCP("tcp", nil, host.addr)
	if err != nil {
		source.Close()
		logger.Printf("connect to %s failed: %s", host.addr, err.Error())
		return
	}

	source.SetKeepAlive(true)
	source.SetKeepAlivePeriod(time.Second * 60)
	source.SetLinger(-1)
	dest.SetLinger(-1)

	go forward(source, dest)
	forward(dest, source)
	//logger.Printf("forward finished, %v -> %v", source.RemoteAddr(), host)
}
開發者ID:no2key,項目名稱:gopf,代碼行數:31,代碼來源:gopf.go

示例5: handlerConnection

//處理連接請求
func (this *server) handlerConnection(conn *net.TCPConn) {

	defer logger.CatchException()

	logger.Infof("New connection coming ... IP=%s ", conn.RemoteAddr())

	conn.SetNoDelay(true)                                        //無延遲
	conn.SetKeepAlive(true)                                      //保持激活
	conn.SetReadBuffer(64 * 1024)                                //設置讀緩衝區大小
	conn.SetWriteBuffer(64 * 1024)                               //設置寫緩衝區大小
	conn.SetReadDeadline(time.Now().Add(30000000 * time.Second)) //設置讀超時

	session := network.NewSession(conn)
	defer session.Close()

	for {
		msg, err := session.RecvMSG()
		if err != nil {
			logger.Infof("RecvMsgs IP=%s err=%v", conn.RemoteAddr(), err.Error())
			return
		}

		ret := this.ProcessMessage(session, msg)
		if ret == false {
			return
		}
	}
}
開發者ID:danuxguin,項目名稱:dxnet,代碼行數:29,代碼來源:server.go

示例6: handleClient

func handleClient(source *net.TCPConn) {
	atomic.AddInt32(&daemon.status.actives, 1)
	defer func() {
		atomic.AddInt32(&daemon.status.actives, -1)
		daemon.wg.Done()
	}()

	// read req
	err, req := ReadReq(source)
	if err != nil {
		source.Close()
		Error("conn:%v, read req failed:%v", source.RemoteAddr(), err)
		return
	}

	source.SetKeepAlive(true)
	source.SetKeepAlivePeriod(time.Second * 60)
	source.SetLinger(-1)

	// judge: new conn or reuse conn
	switch req := req.(type) {
	case *NewConnReq:
		Info("new conn request:%v", req)
		onNewConn(source, req)
	case *ReuseConnReq:
		Info("reuse conn request:%v", req)
		onReuseConn(source, req)
	default:
		Info("unknown request:%v", req)
		source.Close()
		return
	}
}
開發者ID:jonesgithub,項目名稱:goscon,代碼行數:33,代碼來源:main.go

示例7: newClientConn

func newClientConn(ls *LeaseServer, raw *net.TCPConn) (*clientConn, error) {
	err := raw.SetKeepAlive(true)
	if err != nil {
		return nil, err
	}
	err = raw.SetNoDelay(true)
	if err != nil {
		return nil, err
	}
	ret := &clientConn{
		id:          incrementAndGet(&ls.clientIdCounter, 1),
		c:           raw,
		d:           gob.NewDecoder(raw),
		e:           gob.NewEncoder(raw),
		req:         ls.req,
		resp:        make(chan response, 20),
		ackLock:     new(sync.Mutex),
		pendingAcks: make(map[uint64]chan bool),
	}
	// send client id
	fmt.Printf("sending id %d\n", ret.id)
	idBuff := make([]byte, 8, 8)
	binary.LittleEndian.PutUint64(idBuff, ret.id)
	ret.c.Write(idBuff)
	fmt.Println("sent")
	return ret, nil
}
開發者ID:jonpugh,項目名稱:maggiefs,代碼行數:27,代碼來源:leaseserver.go

示例8: SetKeepAlive

func SetKeepAlive(c *net.TCPConn, cfg *KeepAliveConfig) error {
	if err := c.SetKeepAlive(cfg.KeepAlive); err != nil {
		return err
	}

	file, err := c.File()
	if err != nil {
		return err
	}

	fd := int(file.Fd())

	if cfg.KeepAliveIdle != 0 {
		if err := setIdle(fd, secs(cfg.KeepAliveIdle)); err != nil {
			return err
		}
	}

	if cfg.KeepAliveCount != 0 {
		if err := setCount(fd, cfg.KeepAliveCount); err != nil {
			return err
		}
	}

	if cfg.KeepAliveInterval != 0 {
		if err := setInterval(fd, secs(cfg.KeepAliveInterval)); err != nil {
			return nil
		}
	}

	return nil
}
開發者ID:delongw,項目名稱:phantom-tcp,代碼行數:32,代碼來源:keepalive.go

示例9: AcceptTCP

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func (server *Server) AcceptTCP(lis *net.TCPListener, i int) {
	var (
		conn *net.TCPConn
		err  error
	)
	for {
		log.Debug("server: accept round: %d", i)
		if conn, err = lis.AcceptTCP(); err != nil {
			// if listener close then return
			log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
			return
		}
		if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
			log.Error("conn.SetKeepAlive() error(%v)", err)
			return
		}
		if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
			log.Error("conn.SetReadBuffer() error(%v)", err)
			return
		}
		if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
			log.Error("conn.SetWriteBuffer() error(%v)", err)
			return
		}
		go server.serveConn(conn, i)
		if i++; i == maxInt {
			i = 0
		}
	}
}
開發者ID:xingskycn,項目名稱:goim,代碼行數:33,代碼來源:server.go

示例10: SetDefaultOptions

func (this *GoServer) SetDefaultOptions(conn *net.TCPConn) {
	conn.SetKeepAlive(true)
	interval, err := time.ParseDuration("45s")
	if err != nil {
		conn.SetKeepAlivePeriod(interval)
	}
	conn.SetNoDelay(true)
}
開發者ID:henglinli,項目名稱:goserver,代碼行數:8,代碼來源:goserver.go

示例11: newTunnel

func newTunnel(conn *net.TCPConn) *Tunnel {
	conn.SetKeepAlive(true)
	conn.SetKeepAlivePeriod(time.Second * 180)

	var tun Tunnel
	tun.Conn = &Conn{conn, bufio.NewReaderSize(conn, 64*1024), bufio.NewWriterSize(conn, 64*1024), nil, nil}
	Info("new tunnel:%s", tun)
	return &tun
}
開發者ID:catding,項目名稱:gotunnel,代碼行數:9,代碼來源:conn.go

示例12: newTunnel

func newTunnel(conn *net.TCPConn) *Tunnel {
	conn.SetKeepAlive(true)
	conn.SetKeepAlivePeriod(time.Second * 10) //we do not keep so long

	var tun Tunnel
	tun.Conn = &Conn{conn, bufio.NewReaderSize(conn, PacketSize), bufio.NewWriterSize(conn, PacketSize), nil, nil}
	Info("new tunnel:%s", tun)
	return &tun
}
開發者ID:netroby,項目名稱:gotunnel,代碼行數:9,代碼來源:conn.go

示例13: SetClientOptions

// Set TCP socket options on a new SMTP connection.
func (s *SMTPService) SetClientOptions(conn *net.TCPConn) error {
	if err := conn.SetKeepAlive(false); err != nil {
		log.Error("%s: SetKeepAlive: %v", conn.RemoteAddr(), err)
		return err
	}
	if err := conn.SetLinger(-1); err != nil {
		log.Error("%s: SetLinger: %v", conn.RemoteAddr(), err)
		return err
	}
	return nil
}
開發者ID:codeslinger,項目名稱:Go25,代碼行數:12,代碼來源:smtp.go

示例14:

func configureConn (conn *net.TCPConn, spec *ConnectionSpec) {
	// these two -- the most important -- are causing problems on my osx/64
	// where a "service unavailable" pops up in the async reads 
	// but we absolutely need to be able to use timeouts.
//			conn.SetReadTimeout(spec.rTimeout);	
//			conn.SetWriteTimeout(spec.wTimeout);	
	conn.SetLinger(spec.lingerspec);
	conn.SetKeepAlive(spec.keepalive);
	conn.SetReadBuffer(spec.rBufSize);
	conn.SetWriteBuffer(spec.wBufSize);
}
開發者ID:evangineer,項目名稱:Go-Redis,代碼行數:11,代碼來源:connection.go

示例15: faiConnection

func faiConnection(conn *net.TCPConn) {
	defer conn.Close()
	var err error

	err = conn.SetKeepAlive(true)
	if err != nil {
		util.Log(0, "ERROR! SetKeepAlive: %v", err)
	}

	var buf bytes.Buffer
	defer buf.Reset()
	readbuf := make([]byte, 4096)
	n := 1
	for n != 0 {
		n, err = conn.Read(readbuf)
		if err != nil && err != io.EOF {
			util.Log(0, "ERROR! Read: %v", err)
		}
		if n == 0 && err == nil {
			util.Log(0, "ERROR! Read 0 bytes but no error reported")
		}

		// Find complete lines terminated by '\n' and process them.
		for start := 0; ; {
			eol := start
			for ; eol < n; eol++ {
				if readbuf[eol] == '\n' {
					break
				}
			}

			// no \n found, append to buf and continue reading
			if eol == n {
				buf.Write(readbuf[start:n])
				break
			}

			// append to rest of line to buffered contents
			buf.Write(readbuf[start:eol])
			start = eol + 1

			buf.TrimSpace()

			util.Log(2, "DEBUG! FAI monitor message from %v: %v", conn.RemoteAddr(), buf.String())
			buf.Reset()
		}
	}

	if buf.Len() != 0 {
		util.Log(2, "DEBUG! Incomplete FAI monitor message (i.e. not terminated by \"\\n\") from %v: %v", conn.RemoteAddr(), buf.String())
	}
}
開發者ID:chrlutz,項目名稱:limux-gosa,代碼行數:52,代碼來源:tftp-susi.go


注:本文中的net.TCPConn.SetKeepAlive方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。