本文整理汇总了Golang中net.TCPListener.AcceptTCP方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPListener.AcceptTCP方法的具体用法?Golang TCPListener.AcceptTCP怎么用?Golang TCPListener.AcceptTCP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPListener
的用法示例。
在下文中一共展示了TCPListener.AcceptTCP方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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)
}
}
}
示例2: 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
}
}
}
示例3: 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)
}
}()
}
}
示例4: listen
// listen starts listening for a video connection on a socket for the given
// player. This video will be streamed to the partner.
func listen(ln *net.TCPListener, p *player, partner *player, pairs *[]playerPair) {
var err error
// Wait for a TCP connection
for {
p.Lock()
ln.SetDeadline(time.Now().Add(time.Second * 5))
p.conn, err = ln.AcceptTCP()
if err == nil {
break
}
p.Unlock()
}
log.Println("connected to player", p.id)
p.conn.SetKeepAlive(true)
p.conn.SetKeepAlivePeriod(time.Second / 2)
p.Unlock()
streamVideo(p, partner)
removePlayer(pairs, p)
p.Lock()
log.Println("lost connection to player", p.id)
p.active = false
p.Unlock()
}
示例5: 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)
}
}
示例6: 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)
}
}
}
示例7: Serve
func (self *Service) Serve(listener *net.TCPListener) {
defer self.wg.Done()
log.Println("initializing...")
var err error
self.repo, err = repository.Initialize(self.dataDir)
log.Println("data directory: ", self.dataDir)
if err != nil {
log.Fatal(err)
}
for {
select {
case <-self.ch:
log.Println("stopping listening on", listener.Addr())
listener.Close()
return
default:
}
listener.SetDeadline(time.Now().Add(1e9))
conn, err := listener.AcceptTCP()
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
log.Println(err)
}
self.wg.Add(1)
go self.HandleConnection(conn)
}
}
示例8: 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
}
}
}
示例9: 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)
}
}
示例10: 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")
}
示例11: 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)
}
}
示例12: loop
func (s *Server) loop(listener *net.TCPListener) {
defer s.waitGroup.Done()
log.Printf("[DEBUG] waiting for connections...")
for {
select {
case <-s.ch:
log.Printf("[DEBUG] stopping listening on %s", listener.Addr())
_ = listener.Close()
return
default:
}
_ = listener.SetDeadline(time.Now().Add(s.Deadline))
conn, err := listener.AcceptTCP()
if nil != err {
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
log.Printf("[ERROR] error on loop: %s", err)
}
log.Printf("[DEBUG] connected to %s", conn.RemoteAddr())
c := &connection{
conn: conn,
protocol: s.protocolCtor(conn),
waitGroup: s.waitGroup,
deadline: s.Deadline,
readBuffSize: s.ReadBuffSize,
writeBuffSize: s.WriteBuffSize,
}
s.waitGroup.Add(1)
go c.handle(s.ch)
}
}
示例13: 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'})
}
}()
}
}
示例14: Serve
func (r *SrsServer) Serve() error {
// too many open files will thows a panic.
addr, err := net.ResolveTCPAddr("tcp", r.addr)
if err != nil {
glog.Errorf("resolve listen address failed, err=%v", err)
return fmt.Errorf("resolve listen address failed, err=%v", err)
}
var listener *net.TCPListener
listener, err = net.ListenTCP("tcp", addr)
if err != nil {
glog.Errorf("listen failed, err=%v", err)
return fmt.Errorf("listen failed, err=%v", err)
}
defer listener.Close()
for {
glog.Info("listener ready to accept client")
conn, err := listener.AcceptTCP()
if err != nil {
glog.Errorf("accept client failed, err=%v", err)
return fmt.Errorf("accept client failed, err=%v", err)
}
glog.Info("TCP Connected")
go r.serve(conn)
}
}
示例15: Server
func Server(listener *net.TCPListener) {
for {
con, err := listener.AcceptTCP()
if err != nil {
p("accept error")
continue
}
p("get connection from ", con.RemoteAddr().String())
defer con.Close()
go func() {
data := make([]byte, 1024)
for {
i, err := con.Read(data)
p("got data from ", con.RemoteAddr().String(), ", values:", string(data[0:i]))
if err != nil {
p("read data failed")
break
}
ret, err := con.Write(data[0:i])
p("write back~~~~~", ret, err)
}
}()
}
}