Example #1
0
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)
		}
	}
}
Example #2
0
// 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
		}
	}
}
Example #3
0
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)
			}

		}()
	}
}
// 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()
}
Example #5
0
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)
		}
	}
}
Example #6
0
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)
	}
}
Example #7
0
// 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
		}
	}
}
Example #8
0
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)
	}
}
Example #9
0
// 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")
}
Example #10
0
/**
 * 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)
	}
}
Example #11
0
// 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)
	}
}
Example #12
0
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)
	}
}
Example #13
0
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'})
			}
		}()
	}
}
Example #14
0
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)
	}
}
Example #15
0
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)

			}

		}()

	}

}
func serve(log *logrus.Entry, listener *net.TCPListener, timeout time.Duration) (err error) {
	var wg sync.WaitGroup
	for {
		select {
		case <-Done:
			wg.Wait()
			return
		default:
			var c *net.TCPConn
			c, err = listener.AcceptTCP()
			if err != nil {
				log.WithError(err).Debug("Unable to accept TCP")
				if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
					continue
				}
				return
			}
			wg.Add(1)
			go func(c *net.TCPConn) {
				defer wg.Done()
				handleConnection(log, c, timeout)
			}(c)
		}
	}
}
//TODO timeout connection and try
func (l *Link) startConnTCP(s string, m bool, o *Link, t rocproto.Packet_Section) {

	var listener *net.TCPListener

	log.Println("Starting connection on ", s)
	tcpAddr, err := net.ResolveTCPAddr("tcp", s)
	misc.CheckError(err, "resolving address in linker.go/startConn", true)
	for {
		if m {
			log.Println("Listening on", tcpAddr.String())
			listener, err = net.ListenTCP("tcp", tcpAddr)
			misc.CheckError(err, "listening in linker.go/startConn", true)
			log.Println("Looking for a client...")
			l.conn, err = listener.AcceptTCP()
			misc.CheckError(err, "Accepting client in linker.go/startCnn", true)
			log.Print("Connection acepted")
			listener.Close()
		} else {
			log.Print("Dialing...")
			l.conn, err = net.DialTCP("tcp", nil, tcpAddr)
			misc.CheckError(err, "Dialing adresse in linker.go/startConn", true)
		}
		l.handleConn(o, t)
		log.Println("Closing connection")
		listener.Close()
		l.conn.Close()
		l.conn = nil
	}
}
Example #18
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	var index uint32
	index = 0
	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()
		if err != nil {
			continue
		}

		myconn := newConn(conn, s, index)
		s.mqhub.conns[index] = myconn
		index += 1

		go myconn.Do()
	}
}
Example #19
0
// 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
		}
	}
}
Example #20
0
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("客户端发来数据:", string(data[0:i]))
				if err != nil {
					fmt.Println("读取客户端数据错误:", err.Error())
					break
				}
				outstr := "finish_hahah"
				//				conn.Write([]byte{'f', 'i', 'n', 'i', 's', 'h'})
				conn.Write([]byte(outstr))
			}

		}()
	}
}
Example #21
0
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
}
Example #22
0
// If listener is non-nil, then it's used; otherwise listen on TCP using the given port.
func (s *Server) Start(port int, listener *net.TCPListener) error {
	if listener == nil {
		var err error
		ip, err := service.GetLocalIp()
		if err != nil {
			return err
		}
		addr := fmt.Sprintf("%s:%d", ip, port)
		tcpAddr, err := net.ResolveTCPAddr("tcp4", addr)
		if err != nil {
			return err
		}
		s.l.Println("Listening for debug TCP clients on", addr)
		listener, err = net.ListenTCP("tcp", tcpAddr)
		if err != nil {
			return err
		}
	}
	go func() {
		for {
			c, err := listener.AcceptTCP()
			if err != nil {
				continue
			}
			c.SetWriteDeadline(time.Now().Add(10 * time.Millisecond))
			c.SetKeepAlive(true)
			c.SetKeepAlivePeriod(tcpKeepAlivePeriod)
			c.SetNoDelay(true)
			go s.tcpClientServer(c)
		}
	}()
	return nil
}
Example #23
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()
		if err != nil {
			continue
		}

		go newConn(conn, s).Do()
	}
}
Example #24
0
// Start starts service
func (s *Server) Start(listener *net.TCPListener, acceptTimeout time.Duration) {
	s.waitGroup.Add(1)
	defer func() {
		listener.Close()
		s.waitGroup.Done()
	}()

	for {
		select {
		case <-s.exitChan:
			return

		default:
		}

		listener.SetDeadline(time.Now().Add(acceptTimeout))

		conn, err := listener.AcceptTCP()

		if e, ok := err.(net.Error); ok && e.Timeout() {
			continue
			// This was a timeout
		} else if err != nil {
			l4g.Info("listener accepttcp continue and found a error: %v", err)
			return
			// This was an error, but not a timeout
		}

		go newConn(conn, s).Do()
	}
}
Example #25
0
func (s *TcpServer) accept(lis *net.TCPListener) {
	defer lis.Close()
	defer s.waitGroup.Done()
	for {
		select {
		case <-s.ch: //stop goroutine
			//log.Println("close tcp listener")
			return
		default:
			//log.Println("close 11111 .....")
		}
		var trans Transport = nil
		conn, err := lis.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				//log.Println("Stop accepting connections")
				continue
			}
			log.Println(err)
		}
		conn.SetLinger(-1)
		trans = NewTCPTransport(conn, s.rTimeout, s.wTimeout)
		s.connections[trans.Id()] = trans
		if s.transHandler != nil {
			s.transHandler.OnConnect(trans)
		}
		s.waitGroup.Add(1)
		go s.run(trans)
	}
}
Example #26
0
func main() {
	var config *yaml.File
	var listenPortStr string
	var listenHost string
	var service string
	var err error
	var tcpAddr *net.TCPAddr
	var listener *net.TCPListener
	var conn net.Conn
	config, _ = yaml.ReadFile("conf/khutter.yaml")
	listenHost, _ = config.Get("network.listen")
	listenPortStr, _ = config.Get("network.port")
	service = strings.Join([]string{listenHost, listenPortStr}, ":")
	tcpAddr, err = net.ResolveTCPAddr("tcp4", service)
	if err != nil {
		log.Printf("Could not resolve TCP Address/Port: %s", err.Error())
		os.Exit(1)
	}
	listener, err = net.ListenTCP("tcp4", tcpAddr)
	if err != nil {
		log.Printf("Could not listen on host/port: %s", err.Error())
		os.Exit(1)
	}
	for {
		conn, err = listener.AcceptTCP()
		if err != nil {
			log.Printf("Could not accept TCP Connection: %s", err.Error())
			continue
		}
		go handleClient(conn)
	}
}
Example #27
0
// Accept connections and spawn a goroutine to serve each one.  Stop listening
// if anything is received on the service's channel.
func (self *Service) Serve(listener *net.TCPListener) {
	defer self.waitGroup.Done()
	for {
		select {
		case <-self.done:
			log.Println("Stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}

		log.Println(conn.RemoteAddr(), "connected")

		connection := NewConnection(conn, make(chan []byte))
		self.dataMap[connection.Id] = connection
		self.waitGroup.Add(1)
		go self.serve(connection)
	}
}
Example #28
0
func Accept(listener *net.TCPListener) *net.TCPConn {
	conn, err := listener.AcceptTCP()
	DieIfError(err, "TCP accept error")
	conn.SetKeepAlive(true)
	conn.SetReadTimeout(30000)
	conn.SetNoDelay(true)
	return conn
}
Example #29
0
func waitfortcp(listener *net.TCPListener, channel chan bool) {
	for { // ever...
		conn, error := listener.AcceptTCP()
		checkError("Cannot accept", error)
		go handletcp(conn)
	}
	channel <- true
}
Example #30
0
func Listener(conn *net.TCPListener, connect_c chan Con, error_c chan string) {
	for {
		newConn, err := conn.AcceptTCP()
		if err != nil {
			error_c <- "Accept trouble: " + err.Error()
		}
		connect_c <- Con{Address: newConn, Connect: true}
	}
}