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


Golang Conn.SetReadDeadline方法代碼示例

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


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

示例1: connectToDest

func (p *multiplexer) connectToDest(frm *frame, key string, tun *Conn) {
	defer func() {
		ex.CatchException(recover())
	}()
	var (
		dstConn net.Conn
		err     error
		target  = string(frm.data)
	)
	dstConn, err = net.DialTimeout("tcp", target, GENERAL_SO_TIMEOUT)
	frm.length = 0
	if err != nil {
		p.router.removePreRegistered(key)
		log.Errorf("Cannot connect to [%s] for %s error: %s\n", target, key, err)
		frm.action = FRAME_ACTION_OPEN_N
		tunWrite2(tun, frm)
	} else {
		if log.V(1) {
			log.Infoln("OPEN", target, "for", key)
		}
		dstConn.SetReadDeadline(ZERO_TIME)
		edge := p.router.register(key, target, tun, dstConn, false) // write edge
		frm.action = FRAME_ACTION_OPEN_Y
		if tunWrite2(tun, frm) == nil {
			p.relay(edge, tun, frm.sid) // read edge
		} else { // send open_y failed
			SafeClose(tun)
		}
	}
}
開發者ID:hangim,項目名稱:deblocus,代碼行數:30,代碼來源:multiplexer.go

示例2: NewConnection

// NewConnection creates a SSMP connection out of a streaming netwrok connection.
//
// This method blocks until either a first message is received or a 10s timeout
// elapses.
//
// Each accepted connection spawns a goroutine continuously reading from the
// underlying network connection and triggering the Dispatcher. The caller must
// keep track of the returned Connection and call the Close method to stop the
// read goroutine and close the udnerlying netwrok connection.
//
// errInvalidLogin is returned if the first message is not a well-formed LOGIN
// request.
// errUnauthorized is returned if the authenticator doesn't accept the provided
// credentials.
func NewConnection(c net.Conn, a Authenticator, d *Dispatcher) (*Connection, error) {
	r := ssmp.NewDecoder(c)
	c.SetReadDeadline(time.Now().Add(10 * time.Second))
	verb, err := r.DecodeVerb()
	if err != nil || !ssmp.Equal(verb, ssmp.LOGIN) {
		return nil, ErrInvalidLogin
	}
	user, err := r.DecodeId()
	if err != nil {
		return nil, ErrInvalidLogin
	}
	scheme, err := r.DecodeId()
	if err != nil {
		return nil, ErrInvalidLogin
	}
	var cred []byte
	if r.AtEnd() {
		cred = []byte{}
	} else if cred, err = r.DecodePayload(); err != nil {
		return nil, ErrInvalidLogin
	}
	if !a.Auth(c, user, scheme, cred) {
		return nil, ErrUnauthorized
	}
	r.Reset()
	cc := &Connection{
		c:    c,
		r:    r,
		User: string(user),
	}
	go cc.readLoop(d)
	cc.Write(respOk)
	return cc, nil
}
開發者ID:jmptrader,項目名稱:lipwig,代碼行數:48,代碼來源:connection.go

示例3: processConnection

func (cons *Socket) processConnection(conn net.Conn) {
	cons.AddWorker()
	defer cons.WorkerDone()
	defer conn.Close()

	buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)

	for cons.IsActive() && !cons.IsFuseBurned() {
		conn.SetReadDeadline(time.Now().Add(cons.readTimeout))
		err := buffer.ReadAll(conn, cons.Enqueue)
		if err == nil {
			if err = cons.sendAck(conn, true); err == nil {
				continue // ### continue, all is well ###
			}
		}

		// Silently exit on disconnect/close
		if !cons.IsActive() || shared.IsDisconnectedError(err) {
			return // ### return, connection closed ###
		}

		// Ignore timeout related errors
		if netErr, isNetErr := err.(net.Error); isNetErr && netErr.Timeout() {
			continue // ### return, ignore timeouts ###
		}

		Log.Error.Print("Socket transfer failed: ", err)
		cons.sendAck(conn, false)

		// Parser errors do not drop the connection
		if err != shared.BufferDataInvalid {
			return // ### return, close connections ###
		}
	}
}
開發者ID:jrossi,項目名稱:gollum,代碼行數:35,代碼來源:socket.go

示例4: handleClient

func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	defer conn.Close()

	b := bufio.NewReader(conn)

	for {
		status, err := b.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				fmt.Println("Client Disconnected.")
			} else {
				fmt.Println(err)
			}
			break
		}

		// Clean up the input
		status = strings.Replace(status, "\r", "", -1)
		status = strings.Replace(status, "\n", "", -1)

		switch status {
		case "register":
			fmt.Println("Registered")
			conn.Write([]byte("Registered Client\n"))
			break
		default:
			break
		}
	}
}
開發者ID:dfalgout,項目名稱:cdd,代碼行數:31,代碼來源:store.go

示例5: connectToStdio

func connectToStdio(stdin <-chan string, conn net.Conn) {
	go func() {

	}()

	buf := make([]byte, 1024)
	for {
		conn.SetReadDeadline(time.Now().Add(time.Millisecond))
		n, err := conn.Read(buf[0:])
		if err != nil {
			nerr, ok := err.(net.Error)
			if !ok || !nerr.Timeout() {
				log.Println(err)
				return
			}
		}
		os.Stdout.Write(buf[:n])

		select {
		case msg := <-stdin:
			_, err := conn.Write([]byte(msg))
			if err != nil {
				return
			}
		default:
		}
	}
}
開發者ID:modulexcite,項目名稱:relaysrv,代碼行數:28,代碼來源:main.go

示例6: ReadMessage

func ReadMessage(conn net.Conn, timeout time.Duration) (*Message, error) {
	conn.SetReadDeadline(time.Now().Add(DefaultHeartbeatTimeout))
	var lengthBuf [2]byte
	_, err := conn.Read(lengthBuf[:])
	if err != nil {
		return nil, err
	}

	length := int(binary.BigEndian.Uint16(lengthBuf[:]))
	if length > DefaultMessageLengthCap {
		return nil, errors.New("message is too long")
	}

	buf := bytes.NewBuffer(make([]byte, 0, length))
	_, err = io.CopyN(buf, conn, int64(length))
	if err != nil {
		return nil, err
	}

	var handle = &codec.MsgpackHandle{}
	var decoder = codec.NewDecoder(buf, handle)
	var result = &Message{}
	err = decoder.Decode(result)
	if err != nil {
		return nil, err
	}

	return result, nil
}
開發者ID:postman0,項目名稱:xep,代碼行數:29,代碼來源:executor.go

示例7: handleClient

func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()
	for {
		read_len, err := conn.Read(request)
		fmt.Println(read_len)
		if err != nil {
			fmt.Println(err)
			break
		}

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

		request = make([]byte, 128)
	}
}
開發者ID:delaemon,項目名稱:go-socket,代碼行數:25,代碼來源:server.go

示例8: handleConn

func handleConn(conn net.Conn) {
	defer conn.Close()
	for {
		conn.SetReadDeadline(time.Now().Add(10 * time.Second))
		strReq, err := read(conn)
		if err != nil {
			if err == io.EOF {
				fmt.Println("The connection is closed by another side. (Server)")
			} else {
				fmt.Printf("Read Error: %s (Server)\n", err)
			}
			break
		}
		fmt.Printf("Received request: %s (Server)\n", strReq)

		i32Req, err := strconv.Atoi(strReq)
		if err != nil {
			n, err := write(conn, err.Error())
			if err != nil {
				fmt.Printf("Write Eoor (writen %d bytes:) %s (Server)\n", err)
			}
			fmt.Printf("Sent response (written %d bytes %s (server)\n", n, err)
			continue
		}

		f64Resp := math.Cbrt(float64(i32Req))
		respMsg := fmt.Sprintf("The cube root of %d is %f.", i32Req, f64Resp)
		n, err := write(conn, respMsg)
		if err != nil {
			fmt.Printf("Write Error: %s (Server)\n", err)
		}
		fmt.Printf("Sent response (writtn %d bytes:) %s (Server)\n", n, respMsg)
	}
}
開發者ID:xuxiaohu,項目名稱:gosocket,代碼行數:34,代碼來源:server.go

示例9: testRacyRead

// testRacyRead tests that it is safe to mutate the input Read buffer
// immediately after cancelation has occurred.
func testRacyRead(t *testing.T, c1, c2 net.Conn) {
	go chunkedCopy(c2, rand.New(rand.NewSource(0)))

	var wg sync.WaitGroup
	defer wg.Wait()

	c1.SetReadDeadline(time.Now().Add(time.Millisecond))
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			b1 := make([]byte, 1024)
			b2 := make([]byte, 1024)
			for j := 0; j < 100; j++ {
				_, err := c1.Read(b1)
				copy(b1, b2) // Mutate b1 to trigger potential race
				if err != nil {
					checkForTimeoutError(t, err)
					c1.SetReadDeadline(time.Now().Add(time.Millisecond))
				}
			}
		}()
	}
}
開發者ID:phuslu,項目名稱:net,代碼行數:27,代碼來源:conntest.go

示例10: conn_read

// ----------------------------------------------------------------------
//
//   RECEIVE LOGIC
//
// ----------------------------------------------------------------------
func conn_read(conn net.Conn, timeout time.Duration, buffer []byte) (int, error) {
	if timeout != time.Duration(0) {
		conn.SetReadDeadline(time.Now().Add(timeout))
	}

	position := 0
	length := len(buffer)

	for position < length {
		bytesRead, err := conn.Read(buffer[position:])
		if err != nil {
			if err == io.EOF {
				log.Println("conn_read", "CLOSED")
				return 0, CHANNEL_CLOSED
			} else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
				log.Println("conn_read", "TIMEOUT")
				return 0, CHANNEL_TIMEOUT
			} else {
				// we should do better than this
				log.Println("conn_read", err)
				return 0, CHANNEL_CLOSED
			}
		} else {
			position += bytesRead
		}
	}

	return position, nil
}
開發者ID:raff,項目名稱:fd-multiplex,代碼行數:34,代碼來源:multiplex.go

示例11: monitorConnection

// monitorConnection is called for bidi connections and watches for the client
// to disappear. this func blocks until the connection closes or generates a
// a non-timeout error (possibly protocol related).
func (w *Writer) monitorConnection(conn net.Conn) {
	defer close(w.finish)
	var err error
	for {
		conn.SetReadDeadline(time.Now().Add(1 * time.Second))

		// test the connection by attempting to read a FINISH control frame.
		// we should only see this if we've initiated a close by sending a
		// STOP, but it doesn't hurt to start watching for this before then
		// because we're really not expecting the client to send anything
		// else at this point. we also don't have to write anything special
		// back to the client if we receive it because the client closes their
		// end of the connection upon sending.
		_, err = w.readControl(ControlTypeFinish)
		if err == io.EOF {
			// connection closed
		} else if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
			// timeout
			time.Sleep(5 * time.Second) // TODO(jdef) extract constant
			continue
		}
		break
	}
	w.setError(err)
}
開發者ID:jdef,項目名稱:framestream,代碼行數:28,代碼來源:writer.go

示例12: NewConn

func NewConn(client *Client, network, addr string, connectTimeout, readTimeout, writeTimeout time.Duration) (*Conn, error) {
	client.CountNewConn++
	var conn net.Conn
	var err error
	if connectTimeout > 0 {
		conn, err = net.DialTimeout(network, addr, connectTimeout)
	} else {
		conn, err = net.Dial(network, addr)
	}
	if err != nil {
		return nil, err
	}
	if readTimeout > 0 {
		conn.SetReadDeadline(time.Now().Add(readTimeout))
	}
	if writeTimeout > 0 {
		conn.SetWriteDeadline(time.Now().Add(writeTimeout))
	}
	this := &Conn{
		Conn:         conn,
		Client:       client,
		ReadTimeout:  readTimeout,
		WriteTimeout: writeTimeout,
	}
	return this, nil
}
開發者ID:najeira,項目名稱:httpload,代碼行數:26,代碼來源:httpload.go

示例13: copyBytes

func copyBytes(dst, src net.Conn, wg *sync.WaitGroup, writeDeadline, readDeadline time.Duration) {
	defer wg.Done()
	n, err := io.Copy(dst, src)
	if err != nil {
		log.Errorf("proxy i/o error: %v", err)
	}

	if cr, ok := src.(*net.TCPConn); ok {
		cr.CloseRead()
	} else {
		// For TLS connections.
		wto := time.Now().Add(writeDeadline)
		src.SetWriteDeadline(wto)
	}

	if cw, ok := dst.(*net.TCPConn); ok {
		cw.CloseWrite()
	} else {
		// For TLS connections.
		rto := time.Now().Add(readDeadline)
		dst.SetReadDeadline(rto)
	}

	log.Debugf("proxy copied %d bytes %s -> %s", n, src.RemoteAddr(), dst.RemoteAddr())
}
開發者ID:Celluliodio,項目名稱:flannel,代碼行數:25,代碼來源:proxy.go

示例14: handleConnection

func handleConnection(conn net.Conn) {
	defer conn.Close()
	conn.SetReadDeadline(time.Now().Add(time.Second * 3))

	r := bufio.NewReader(conn)

	size, err := r.ReadString(';')
	if err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to read content length: %v\n", err)
		return
	}

	size = size[:len(size)-1]
	i, err := strconv.Atoi(size)
	if err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to get content length from %s: %v\n", size, err)
		return
	}

	b := make([]byte, i)
	r.Read(b)

	intent := content.Intent{}
	if err := json.Unmarshal(b, &intent); err != nil {
		log.Println(err)
		fmt.Fprintf(conn, "Failed to decode request: %v", err)
	}

	content.Handle(conn, intent)
}
開發者ID:berkus,項目名稱:completion,代碼行數:32,代碼來源:server.go

示例15: proxy

func (s *session) proxy(c1, c2 net.Conn) error {
	if debug {
		log.Println("Proxy", c1.RemoteAddr(), "->", c2.RemoteAddr())
	}

	atomic.AddInt64(&numProxies, 1)
	defer atomic.AddInt64(&numProxies, -1)

	buf := make([]byte, 65536)
	for {
		c1.SetReadDeadline(time.Now().Add(networkTimeout))
		n, err := c1.Read(buf)
		if err != nil {
			return err
		}

		atomic.AddInt64(&bytesProxied, int64(n))

		if debug {
			log.Printf("%d bytes from %s to %s", n, c1.RemoteAddr(), c2.RemoteAddr())
		}

		if s.rateLimit != nil {
			s.rateLimit(int64(n))
		}

		c2.SetWriteDeadline(time.Now().Add(networkTimeout))
		_, err = c2.Write(buf[:n])
		if err != nil {
			return err
		}
	}
}
開發者ID:alex2108,項目名稱:relaysrv,代碼行數:33,代碼來源:session.go


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