当前位置: 首页>>代码示例>>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;未经允许,请勿转载。