示例#1
0
// threadedAcceptConn adds a connecting node as a peer.
func (g *Gateway) threadedAcceptConn(conn net.Conn) {
	if g.threads.Add() != nil {
		conn.Close()
		return
	}
	defer g.threads.Done()
	conn.SetDeadline(time.Now().Add(connStdDeadline))

	addr := modules.NetAddress(conn.RemoteAddr().String())
	g.log.Debugf("INFO: %v wants to connect", addr)

	remoteVersion, err := acceptConnVersionHandshake(conn, build.Version)
	if err != nil {
		g.log.Debugf("INFO: %v wanted to connect but version handshake failed: %v", addr, err)
		conn.Close()
		return
	}

	if build.VersionCmp(remoteVersion, handshakeUpgradeVersion) < 0 {
		err = g.managedAcceptConnOldPeer(conn, remoteVersion)
	} else {
		err = g.managedAcceptConnNewPeer(conn, remoteVersion)
	}
	if err != nil {
		g.log.Debugf("INFO: %v wanted to connect, but failed: %v", addr, err)
		conn.Close()
		return
	}
	// Handshake successful, remove the deadline.
	conn.SetDeadline(time.Time{})

	g.log.Debugf("INFO: accepted connection from new peer %v (v%v)", addr, remoteVersion)
}
示例#2
0
// Handles incoming requests for both TCP and UDP
func handleGraphiteTextProtocol(t *trTransceiver, conn net.Conn, timeout int) {

	defer conn.Close() // decrements tcpWg

	if timeout != 0 {
		conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
	}

	// We use the Scanner, becase it has a MaxScanTokenSize of 64K

	connbuf := bufio.NewScanner(conn)

	for connbuf.Scan() {
		packetStr := connbuf.Text()

		if dp, err := parseGraphitePacket(packetStr); err != nil {
			log.Printf("handleGraphiteTextProtocol(): bad backet: %v")
		} else {
			t.queueDataPoint(dp)
		}

		if timeout != 0 {
			conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
		}
	}

	if err := connbuf.Err(); err != nil {
		log.Println("handleGraphiteTextProtocol(): Error reading: %v", err)
	}
}
示例#3
0
func handleCient(conn net.Conn) {
	conn.SetDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()

	for {
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s", err)
			break
		}

		fmt.Printf(string(read_len))

		// if read_len == 0 {
		// 	break
		// } else if string(request) == "timestamp" {
		daytime := time.Now().String()
		conn.Write([]byte(daytime))
		// }
	}

	request = make([]byte, 128)
}
// 客户端连接的处理逻辑。 首先握手,握手失败关闭连接;然后读数据,写入 Dispatcher 的处理队列。
func Handler(conn net.Conn, hsPwd string, inputChid string) {
	defer conn.Close()

	chid := ""
	if len(inputChid) < 1 {
		ch, recvers, err := HandShake(conn, hsPwd)
		if err != nil {
			return
		}
		chid = ch
		createConnQ <- &ConnInfo{conn, chid, 600, recvers}
	} else {
		chid = inputChid
		createConnQ <- &ConnInfo{conn, chid, 0, nil}
	}

	for {
		data := make([]byte, 1048576)
		n, err := conn.Read(data) // 读出数据,放入 Dispatcher 的发送队列
		if err != nil {           // 关闭时给 Dispatcher 发送通知
			if err == io.EOF {
				log.Println("Connection closed!")
			} else {
				log.Println("Read error: ", err)
			}
			removeConnQ <- chid
			break
		}
		conn.SetDeadline(time.Now().Add(time.Duration(120) * time.Second))
		log.Println("Read data:", string(data[:n]))
		sendQ <- SendQEle{chid, bytes.NewBuffer(data[:n])}
	}
}
示例#5
0
// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, timeout time.Duration) {
	defer svrConn.Close()
	var buffer [4096]byte
	for {
		n, err := svrConn.Read(buffer[0:])
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("Read failed: %v", err)
			}
			break
		}
		svrConn.SetDeadline(time.Now().Add(timeout))
		if err != nil {
			glog.Errorf("SetDeadline failed: %v", err)
			break
		}
		n, err = udp.WriteTo(buffer[0:n], cliAddr)
		if err != nil {
			if !logTimeout(err) {
				glog.Errorf("WriteTo failed: %v", err)
			}
			break
		}
	}
	activeClients.mu.Lock()
	delete(activeClients.clients, cliAddr.String())
	activeClients.mu.Unlock()
}
示例#6
0
func (p *Proxy) handleMessage(h *messageHeader, client, server net.Conn) error {
	deadline := time.Now().Add(p.messageTimeout)
	server.SetDeadline(deadline)
	client.SetDeadline(deadline)

	if h.OpCode == OpQuery {
		return p.handleQueryRequest(h, client, server)
	}

	if err := h.WriteTo(server); err != nil {
		log.Println(err)
		return err
	}

	if _, err := io.CopyN(server, client, int64(h.MessageLength-headerLen)); err != nil {
		log.Println(err)
		return err
	}

	if h.OpCode.HasResponse() {
		if err := copyMessage(client, server); err != nil {
			log.Println(err)
			return err
		}
	}

	return nil
}
示例#7
0
文件: web.go 项目: cairobert/webmon
// called in a go statement
func serveConn(conn net.Conn, stmt *sql.Stmt) {
	defer conn.Close()
	log.Print(conn.RemoteAddr(), " connected to server...")
	ret := make([]byte, 1500)
	conn.SetDeadline(time.Now().Add(10 * time.Second))
	n, err := conn.Read(ret)
	if err != nil {
		log.Print("error in reading: ", err)
		return
	}
	var cmds []interface{}
	err = json.Unmarshal(ret[:n], &cmds)
	if err != nil {
		log.Print("Fail to parse results")
		return
	}
	if _, ok := cmds[0].(string); !ok {
		log.Print("error in serveConn, data format that clients send is wrong")
		return
	}
	cmd := cmds[0].(string)
	switch cmd {
	case "INIT":
		initNode(conn, stmt)
	case "MONITOR":
		parseResults(cmds)
	default:
		log.Print("Unknown command: ", cmds)
	}
}
示例#8
0
// Handle triggers the collect-metrics hook and writes collected metrics
// to the specified connection.
func (l *handler) Handle(c net.Conn) (err error) {
	defer func() {
		if err != nil {
			fmt.Fprintf(c, "%v\n", err.Error())
		} else {
			fmt.Fprintf(c, "ok\n")
		}
		c.Close()
	}()
	// TODO(fwereade): 2016-03-17 lp:1558657
	err = c.SetDeadline(time.Now().Add(spool.DefaultTimeout))
	if err != nil {
		return errors.Annotate(err, "failed to set the deadline")
	}
	recorder, err := l.config.metricsFactory.Recorder(
		l.config.validMetrics,
		l.config.charmURL.String(),
		l.config.unitTag.String(),
	)
	if err != nil {
		return errors.Annotate(err, "failed to create the metric recorder")
	}
	defer recorder.Close()
	err = l.config.runner.do(recorder)
	if err != nil {
		return errors.Annotate(err, "failed to collect metrics")
	}
	return nil
}
示例#9
0
文件: net.go 项目: bfix/gospel
// RecvData receives data over network connection (stream-oriented).
func RecvData(conn net.Conn, data []byte, srv string) (int, bool) {

	for retry := 0; retry < retries; {
		// set timeout
		conn.SetDeadline(time.Now().Add(timeout))
		// read data from socket buffer
		n, err := conn.Read(data)
		if err != nil {
			// handle error condition
			switch err.(type) {
			case net.Error:
				// network error: retry...
				nerr := err.(net.Error)
				if nerr.Timeout() {
					return 0, true
				} else if nerr.Temporary() {
					retry++
					time.Sleep(delay)
					continue
				}
			default:
				logger.Printf(logger.INFO, "[%s] Connection closed by peer\n", srv)
				return 0, false
			}
		}
		// report success
		if retry > 0 {
			logger.Printf(logger.INFO, "[%s] %d retries needed to receive data.\n", srv, retry)
		}
		return n, true
	}
	// retries failed
	logger.Printf(logger.ERROR, "[%s] Read failed after retries...\n", srv)
	return 0, false
}
示例#10
0
文件: policy.go 项目: simonz05/policy
func handle(conn net.Conn) {
	defer conn.Close()

	err := conn.SetDeadline(time.Now().Add(Timeout))

	if err != nil {
		log.Errorf("Error setting deadline on conn")
		return
	}

	buf := getBuf(bufSize)
	defer putBuf(buf)

	n, err := conn.Read(buf)

	if err != nil {
		log.Error("Error reading from conn")
		return
	}

	log.Printf("Got %+q", buf[:n])
	resp, err := parseRequest(buf[:n])

	if err != nil {
		log.Error(err)
		return
	}

	n, err = conn.Write(resp)

	if err != nil || n != len(resp) {
		log.Errorf("Error writing to conn")
		return
	}
}
示例#11
0
文件: net.go 项目: mantyr/Sia
// TODO: maintain compatibility
func (h *Host) handleConn(conn net.Conn) {
	defer conn.Close()
	// Set an initial duration that is generous, but finite. RPCs can extend
	// this if so desired.
	conn.SetDeadline(time.Now().Add(5 * time.Minute))

	var id types.Specifier
	if err := encoding.ReadObject(conn, &id, 16); err != nil {
		return
	}
	var err error
	switch id {
	case modules.RPCSettings:
		err = h.rpcSettings(conn)
	case modules.RPCUpload:
		err = h.rpcUpload(conn)
	case modules.RPCRevise:
		err = h.rpcRevise(conn)
	case modules.RPCDownload:
		err = h.rpcDownload(conn)
	default:
		h.log.Printf("WARN: incoming conn %v requested unknown RPC \"%v\"", conn.RemoteAddr(), id)
		return
	}
	if err != nil {
		h.log.Printf("WARN: incoming RPC \"%v\" failed: %v", id, err)
	}
}
示例#12
0
func (ctr *Controller) request(conn net.Conn) (err error) {
	log.Print("ctr.request:")
	var iniStr = []interface{}{"INIT"}
	sends, err := json.Marshal(iniStr)
	if err != nil {
		log.Print("error in request: ", err)
		return
	}
	_, err = conn.Write(sends) // fisrt send the INIT and local addr to it
	if err != nil {
		log.Print("conn.Write(): ", err)
		return
	}
	conn.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))
	defer func() {
		var zero time.Time
		conn.SetDeadline(zero)
	}()

	ret := make([]byte, 1500)
	n, err := conn.Read(ret)
	if err != nil {
		log.Print("conn.Read(): ", err)
		return
	}
	id := -1
	err = json.Unmarshal(ret[:n], &id) // fetch id
	if err != nil {
		log.Print("Fail to communicate with server: ", err)
		return
	}
	ctr.id = id
	go ctr.Listen(ctr.QUIT)
	return nil
}
示例#13
0
func authorize(conn net.Conn) bool {
	tlsConn, ok := conn.(*tls.Conn)
	if !ok {
		return false
	}

	// Force handshake. Handshake usually happens on first read/write, but
	// we want to authenticate before reading/writing so we need to force
	// the handshake to get the client cert. If handshake blocks for more
	// than the timeout, we kill the connection.
	timer := time.AfterFunc(*timeoutDuration, func() {
		logger.Printf("timed out TLS handshake on %s", conn.RemoteAddr())
		conn.SetDeadline(time.Now())
		conn.Close()
		timeoutCounter.Inc(1)
	})

	err := tlsConn.Handshake()
	timer.Stop()
	if err != nil {
		logger.Printf("failed TLS handshake on %s: %s", conn.RemoteAddr(), err)
		errorCounter.Inc(1)
		return false
	}

	return authorized(tlsConn.ConnectionState())
}
示例#14
0
文件: socket.go 项目: oopcode/gollum
func (cons *Socket) readFromConnection(conn net.Conn) {
	defer func() {
		conn.Close()
		cons.WorkerDone()
	}()

	conn.SetDeadline(time.Time{})
	buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)

	for !cons.quit {
		err := buffer.ReadAll(conn, cons.Enqueue)

		// Handle errors
		if err != nil && err != io.EOF {
			if cons.clientDisconnected(err) {
				return // ### return, connection closed ###
			}

			Log.Error.Print("Socket read failed: ", err)
			continue // ### continue, keep open, try again ###
		}

		// Send ack if everything was ok
		if cons.acknowledge != "" {
			fmt.Fprint(conn, cons.acknowledge)
		}
	}
}
示例#15
0
// HandleClient relays a message read from client connection c to mixnet
// connection  d and relay reply.
func (p *ProxyContext) HandleClient(c net.Conn, d *Conn) error {

	msg := make([]byte, MaxMsgBytes)
	c.SetDeadline(time.Now().Add(p.timeout))
	bytes, err := c.Read(msg)
	if err != nil {
		return err
	}

	if err = p.SendMessage(d, msg[:bytes]); err != nil {
		return err
	}

	reply, err := p.ReceiveMessage(d)
	if err != nil {
		return err
	}

	c.SetDeadline(time.Now().Add(p.timeout))
	if _, err = c.Write(reply); err != nil {
		return err
	}

	return nil
}
示例#16
0
// managedRPCSettings is an rpc that returns the host's settings.
func (h *Host) managedRPCSettings(conn net.Conn) error {
	// Set the negotiation deadline.
	conn.SetDeadline(time.Now().Add(modules.NegotiateSettingsTime))

	// The revision number is updated so that the renter can be certain that
	// they have the most recent copy of the settings. The revision number and
	// signature can be compared against other settings objects that the renter
	// may have, and if the new revision number is not higher the renter can
	// suspect foul play. Largely, the revision number is in place to enable
	// renters to share host settings with each other, a feature that has not
	// yet been implemented.
	//
	// While updating the revision number, also grab the secret key and
	// external settings.
	var hes modules.HostExternalSettings
	var secretKey crypto.SecretKey
	h.mu.Lock()
	h.revisionNumber++
	secretKey = h.secretKey
	hes = h.externalSettings()
	h.mu.Unlock()

	// Write the settings to the renter. If the write fails, return a
	// connection error.
	err := crypto.WriteSignedObject(conn, hes, secretKey)
	if err != nil {
		return ErrorConnection("failed WriteSignedObject during RPCSettings: " + err.Error())
	}
	return nil
}
示例#17
0
文件: looktable.go 项目: qingtao/mana
func handler(conn net.Conn, timeout time.Duration, id int64) {
	log.Printf("-- %d --\n", id)
	var buf = bufio.NewReader(conn)
	conn.SetDeadline(time.Now().Add(timeout))
	for {
		line, err := buf.ReadString('\n')
		if err == nil {
			conn.SetDeadline(time.Now().Add(timeout))
			command, req := parse(line)
			res := reply(command, req)
			if command == "quit" {
				fmt.Fprint(conn, res)
				break
			}
			log.Printf("%d Response: %s", id, res)
			fmt.Fprint(conn, res)
		} else {
			break
		}
	}
	if err := conn.Close(); err != nil {
		log.Println("%d conn close error: %s.\n", id, err)
	}
	log.Printf("%d Connection closed.\n", id)
	return
}
示例#18
0
func (p *Reducer) fetchFromBackend(b *Backend) (buffer []byte, err error) {
	var client net.Conn

	b.Ongoing.Add(1)
	b.Hits.Add(1)
	start := time.Now()

	defer func() {
		if err != nil {
			log.Println("server broken", b.Addr, err)
			b.markAsBroken()
			// p.err = err
			// log.Println(b.addr, err)
			b.Fails.Add(1)
			if client != nil {
				client.Close()
			}
		} else {
			b.returnConn(client)
		}
		b.Ongoing.Add(-1)
		latency := time.Since(start)
		b.addLatency(latency)
	}()
	if client, err = b.getConn(time.Millisecond * 100); err != nil {
		return nil, err
	}

	client.SetDeadline(start.Add(time.Minute * 1))
	if err = writeAll(p.req.bytes, client); err != nil {
		return nil, err
	}
	buffer, err = readFramedThrift(client)
	return
}
示例#19
0
func (srv *Server) handlerConn(conn net.Conn) {
	defer func() {
		if err := recover(); err != nil {
			log.Printf("work failed:", err)
		}
	}()
	// 是这里调用关闭还是 Handler() 负责?
	defer conn.Close()

	if tcpConn, ok := conn.(SetLingerer); ok == true {
		// 设置关闭连接时最多等待多少秒
		tcpConn.SetLinger(5)
	}
	conn.SetDeadline(time.Now().Add(handlerNewTimeout))

	h, _, err := srv.hNewer.New(conn)
	if h == nil {
		log.Printf("无法识别请求的协议类型,远端地址:%v,近端地址:%v,详细错误:%v", conn.RemoteAddr(), conn.LocalAddr(), err)
		return
	}

	conn.SetDeadline(time.Now().Add(handlerBaseTimeout))
	if err := h.Handle(); err != nil {
		if err != io.EOF {
			log.Printf("协议处理错误:", err)
		}
	}
}
示例#20
0
// NewActivityMonitoredConn creates a new ActivityMonitoredConn.
func NewActivityMonitoredConn(
	conn net.Conn,
	inactivityTimeout time.Duration,
	activeOnWrite bool,
	activityUpdater ActivityUpdater,
	lruEntry *LRUConnsEntry) (*ActivityMonitoredConn, error) {

	if inactivityTimeout > 0 {
		err := conn.SetDeadline(time.Now().Add(inactivityTimeout))
		if err != nil {
			return nil, ContextError(err)
		}
	}

	now := int64(monotime.Now())

	return &ActivityMonitoredConn{
		Conn:                 conn,
		inactivityTimeout:    inactivityTimeout,
		activeOnWrite:        activeOnWrite,
		realStartTime:        time.Now(),
		monotonicStartTime:   now,
		lastReadActivityTime: now,
		activityUpdater:      activityUpdater,
		lruEntry:             lruEntry,
	}, nil
}
示例#21
0
文件: client.go 项目: xinlaini/golibs
func roundtrip(ctx *ClientContext, conn net.Conn, requestSize, requestBytes []byte) ([]byte, error) {
	deadline, ok := ctx.Deadline()
	if !ok {
		deadline = time.Time{}
	}

	var err error
	if err = conn.SetDeadline(deadline); err != nil {
		return nil, makeClientErr(err.Error())
	}
	if _, err = conn.Write(requestSize); err != nil {
		return nil, makeClientErrf("Failed to write 4 bytes for request size: %s", err)
	}
	if _, err = conn.Write(requestBytes); err != nil {
		return nil, makeClientErrf("Failed to write %d bytes for request: %s", err)
	}
	buf := bytes.NewBuffer(make([]byte, 0, 4))
	if _, err = io.CopyN(buf, conn, 4); err != nil {
		return nil, makeClientErrf(
			"Failed to read 4 bytes for response size from '%s': %s",
			conn.RemoteAddr().String(), err)
	}
	responseSize := binary.BigEndian.Uint32(buf.Bytes())
	if _, err = io.CopyN(buf, conn, int64(responseSize)); err != nil {
		return nil, makeClientErrf(
			"Failed to read %d bytes for response from '%s': %s",
			conn.RemoteAddr().String(), err)
	}
	return buf.Bytes(), nil
}
示例#22
0
文件: stats.go 项目: hudalikawa/govpn
// StatsProcessor is assumed to be run in background. It accepts
// connection on statsPort, reads anything one send to them and show
// information about known peers in serialized JSON format. peers
// argument is a reference to the map with references to the peers as
// values. Map is used here because of ease of adding and removing
// elements in it.
func StatsProcessor(statsPort net.Listener, peers *KnownPeers) {
	var conn net.Conn
	var err error
	var data []byte
	buf := make([]byte, 2<<8)
	for {
		conn, err = statsPort.Accept()
		if err != nil {
			log.Println("Error during accepting connection", err.Error())
			continue
		}
		conn.SetDeadline(time.Now().Add(RWTimeout))
		conn.Read(buf)
		conn.Write([]byte("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n"))
		var peersList []*Peer
		for _, peer := range *peers {
			peersList = append(peersList, *peer)
		}
		data, err = json.Marshal(peersList)
		if err != nil {
			panic(err)
		}
		conn.Write(data)
		conn.Close()
	}
}
示例#23
0
文件: proxy.go 项目: rlugojr/martian
func (p *Proxy) handleLoop(conn net.Conn) {
	p.conns.Add(1)
	defer p.conns.Done()
	defer conn.Close()

	s, err := newSession()
	if err != nil {
		log.Errorf("martian: failed to create session: %v", err)
		return
	}

	ctx, err := withSession(s)
	if err != nil {
		log.Errorf("martian: failed to create context: %v", err)
		return
	}

	brw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	for {
		deadline := time.Now().Add(p.timeout)
		conn.SetDeadline(deadline)

		if err := p.handle(ctx, conn, brw); isCloseable(err) {
			log.Debugf("martian: closing connection: %v", conn.RemoteAddr())
			return
		}
	}
}
示例#24
0
文件: conntest.go 项目: phuslu/net
// testCloseTimeout tests that calling Close immediately times out pending
// Read and Write operations.
func testCloseTimeout(t *testing.T, c1, c2 net.Conn) {
	go chunkedCopy(c2, c2)

	var wg sync.WaitGroup
	defer wg.Wait()
	wg.Add(3)

	// Test for cancelation upon connection closure.
	c1.SetDeadline(neverTimeout)
	go func() {
		defer wg.Done()
		time.Sleep(100 * time.Millisecond)
		c1.Close()
	}()
	go func() {
		defer wg.Done()
		var err error
		buf := make([]byte, 1024)
		for err == nil {
			_, err = c1.Read(buf)
		}
	}()
	go func() {
		defer wg.Done()
		var err error
		buf := make([]byte, 1024)
		for err == nil {
			_, err = c1.Write(buf)
		}
	}()
}
示例#25
0
// Dial and scrape the basic service parameters
func (s *BasicService) dialAndScrape() (net.Conn, error) {
	if s.Timeout == 0 {
		log.Warnln("0 deadline set for service. This is probably not what you want as services will flap.")
	}

	// Set absolute deadline
	deadline := time.Now().Add(time.Duration(s.Timeout))

	// Dialer deadline
	dialer := net.Dialer{
		Deadline: deadline,
	}

	var err error
	var conn net.Conn

	conn, err = dialer.Dial(s.Protocol, fmt.Sprintf("%s:%d", s.Host().Hostname, s.Port()))
	if err != nil {
		s.portOpen = FAILED
	} else {
		s.portOpen = SUCCESS
	}

	if conn != nil {
		// Connection deadline
		conn.SetDeadline(deadline)
	}

	return conn, err
}
示例#26
0
文件: main.go 项目: fimmtiu/gofingerd
// Read user input and send a response on a single client connection.
func handleConnection(conn net.Conn) {
	defer conn.Close()

	conn.SetDeadline(time.Now().Add(conf.NetworkTimeout))
	request, err := readRequest(conn)
	if err != nil {
		log.Printf("ERROR: Can't read from %s: %s", conn.RemoteAddr().String(), err.Error())
		return
	}

	if len(request.Hosts) > 0 {
		if conf.AllowQueryForwarding {
			RespondWithForwardedQuery(conn, request)
		} else {
			log.Printf("Refused forwarding request from %s.", conn.RemoteAddr().String())
			fmt.Fprint(conn, "This server does not permit request forwarding.\r\n")
		}
	} else if len(request.User) == 0 {
		if conf.AllowUserListing {
			RespondWithUserList(conn)
		} else {
			log.Printf("Refused user listing request from %s.", conn.RemoteAddr().String())
			fmt.Fprint(conn, "This server does not permit user listing.\r\n")
		}
	} else if conf.AllowApproximateSearch {
		RespondWithApproximateSearch(conn, request)
	} else {
		RespondWithExactSearch(conn, request)
	}
}
示例#27
0
// TODO isn't this identical to handleGraphiteTextProtocol?
func handleStatsdTextProtocol(t *trTransceiver, conn net.Conn, timeout int) {

	defer conn.Close() // decrements tcpWg

	if timeout != 0 {
		conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
	}

	// We use the Scanner, becase it has a MaxScanTokenSize of 64K

	connbuf := bufio.NewScanner(conn)

	for connbuf.Scan() {
		if stat, err := parseStatsdPacket(connbuf.Text()); err == nil {
			t.queueStat(stat)
		} else {
			log.Printf("parseStatsdPacket(): %v", err)
		}

		if timeout != 0 {
			conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
		}
	}

	if err := connbuf.Err(); err != nil {
		log.Println("handleStatsdTextProtocol(): Error reading: %v", err)
	}
}
示例#28
0
func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
	// TODO: handle/store session token

	// Run setupFunc, which should create an authenticated connection
	// and run the capability exchange. Note that any early error
	// returns during that exchange need to call peerWG.Done because
	// the callers of startPeer added the peer to the wait group already.
	fd.SetDeadline(time.Now().Add(handshakeTimeout))

	conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest, srv.keepconn)
	if err != nil {
		fd.Close()
		glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err)
		srv.peerWG.Done()
		return
	}
	conn.MsgReadWriter = &netWrapper{
		wrapped: conn.MsgReadWriter,
		conn:    fd, rtimeout: frameReadTimeout, wtimeout: frameWriteTimeout,
	}
	p := newPeer(fd, conn, srv.Protocols)
	if ok, reason := srv.addPeer(conn, p); !ok {
		glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
		p.politeDisconnect(reason)
		srv.peerWG.Done()
		return
	}
	// The handshakes are done and it passed all checks.
	// Spawn the Peer loops.
	go srv.runPeer(p)
}
示例#29
0
文件: server.go 项目: dengzhi007/sky
func (this *Server) receive(buf []byte, conn net.Conn) ([]byte, error) {
	conn.SetDeadline(time.Now().Add(this.connTimeout))
	readNum := 0
	length := len(buf)

	var num int
	var err error
	for readNum < length {
		num, err = conn.Read(buf[readNum:])
		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
				time.Sleep(time.Second)
				continue
			}
			return nil, err
		}
		this.logger.Debug("Read %d bytes: %s", num, string(buf))
		readNum += num
	}

	_, err = conn.Write([]byte("ok"))
	if err != nil {
		return nil, err
	}

	return buf, nil
}
示例#30
0
// Read with timeout, then build a request and compute and send a response
// to the client.
//
// Data: < Board serialization >< Stash serialization >< Piece index >
// Size: <     16 * Piece      ><     16 * Piece      ><     uint8   >
// Size in byte is: 33
func handleConnection(conn net.Conn) {
	defer conn.Close()

	// Set a timeout 10 seconds from the connection
	timeout := time.Now().Add(time.Second * 10)
	conn.SetDeadline(timeout)

	msg := make(Message, 33)
	_, err := conn.Read(msg)

	// Error handling
	if err != nil {
		if err.(net.Error).Timeout() {
			fmt.Print("Read timeout, closing connection.\n")
		} else {
			fmt.Printf("Error while reading: %s\n", err.Error())
		}
		return
	}

	request := readMessage(msg)
	if request.isValid() {
		response := handleRequest(request)
		conn.Write(response)
	}
}