// Helper for writing to socket with deadline.
331243
func (conn *Connection) write(mode int, payload []byte) error {
	conn.socket.SetWriteDeadline(time.Now().Add(writeWait))
	return conn.socket.WriteMessage(mode, payload)
}
687592
func (d *dialer) dialer() {
	rtime := d.sock.reconntime
	rtmax := d.sock.reconnmax
	for {
		p, err := d.d.Dial()
		if err == nil {
			// reset retry time
			rtime = d.sock.reconntime
			d.sock.Lock()
			if d.closed {
				d.sock.Unlock()
				p.Close()
				return
			}
			d.sock.Unlock()
			if cp := d.sock.addPipe(p, d, nil); cp != nil {
				select {
				case <-d.sock.closeq: // parent socket closed
				case <-cp.closeq: // disconnect event
				case <-d.closeq: // dialer closed
				}
			}
		}

		// we're redialing here
		select {
		case <-d.closeq: // dialer closed
			if p != nil {
				p.Close()
			}
			return
		case <-d.sock.closeq: // exit if parent socket closed
			if p != nil {
				p.Close()
			}
			return
		case <-time.After(rtime):
			if rtmax > 0 {
				rtime *= 2
				if rtime > rtmax {
					rtime = rtmax
				}
			}
			continue
		}
	}
}
1147974
func (c *Websocket) WithWriteTimeout(timeout time.Duration) *Websocket {
	c.writeTimeout = timeout
	return c
}
616855
func (s *sender) Handle(c net.Conn, _ <-chan struct{}) (err error) {
	defer func() {
		if err != nil {
			fmt.Fprintf(c, "%v\n", err)
		} else {
			fmt.Fprintf(c, "ok\n")
		}
		c.Close()
	}()
	// TODO(fwereade): 2016-03-17 lp:1558657
	if err := c.SetDeadline(time.Now().Add(spool.DefaultTimeout)); err != nil {
		return errors.Annotate(err, "failed to set the deadline")
	}
	reader, err := s.factory.Reader()
	if err != nil {
		return errors.Trace(err)
	}
	defer reader.Close()
	return s.sendMetrics(reader)
}
155365
func (conn *HvsockConn) SetWriteDeadline(t time.Time) error {
	return conn.sock.SetWriteDeadline(t)
}
1043588
func (p *ConnPool) deadlinePassed(deadline *time.Time) bool {
	return deadline != nil && time.Now().After(*deadline)
}
695253
func (nd *Node) makeConnectionForPool(deadline time.Time, hint byte) {
	if deadline.IsZero() {
		deadline = time.Now().Add(_DEFAULT_TIMEOUT)
	}

	// don't even try to make a new connection if connection limit is reached
	if nd.connectionLimitReached() {
		return
	}

L:
	// don't loop forever; free the goroutine after the deadline
	if time.Now().After(deadline) {
		return
	}

	conn, err := nd.newConnection(false)
	if err != nil {
		// The following check can help break the loop under heavy load and remove
		// quite a lot of latency.
		if err == ErrTooManyConnectionsForNode {
			// The connection pool is already full. No need for more connections.
			return
		}

		Logger.Error("Error trying to making a connection to the node %s: %s", nd.String(), err.Error())

		time.Sleep(time.Millisecond)
		goto L
	}

	nd.putConnectionWithHint(conn, hint)
}
342931
func (s *DeadlineStream) WriteJSON(v interface{}) error {
	// This uses a real clock rather than trying to use a clock passed
	// in because the websocket will use a real clock to determine
	// whether the deadline has passed anyway.
	deadline := time.Now().Add(s.Timeout)
	if err := s.Conn.SetWriteDeadline(deadline); err != nil {
		return errors.Annotate(err, "setting write deadline")
	}
	return errors.Trace(s.Conn.WriteJSON(v))
}
978856
func (c *Conn) Write(b []byte) (int, error) {
	if !c.ok() {
		return 0, syscall.EINVAL
	}
	if !c.isOpen() {
		return 0, &net.OpError{
			Op:   "write",
			Net:  c.LocalAddr().Network(),
			Addr: c.LocalAddr(),
			Err:  errClosing,
		}
	}
	c.deadlineMutex.RLock()
	d := timeToDeadline(c.wdeadline)
	c.deadlineMutex.RUnlock()
	return c.writebuf.WriteTimeout(b, d)
}
83541
func WaitUntil(fn ConditionFn, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if fn() {
			return true
		}
		time.Sleep(100 * time.Millisecond)
	}
	return false
}
60194
func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) {
	if err != syscall.ERROR_IO_PENDING {
		return int(bytes), err
	}

	if f.closing.isSet() {
		cancelIoEx(f.handle, &c.o)
	}

	var timeout timeoutChan
	if d != nil {
		d.channelLock.Lock()
		timeout = d.channel
		d.channelLock.Unlock()
	}

	var r ioResult
	select {
	case r = <-c.ch:
		err = r.err
		if err == syscall.ERROR_OPERATION_ABORTED {
			if f.closing.isSet() {
				err = ErrFileClosed
			}
		} else if err != nil && f.socket {
			// err is from Win32. Query the overlapped structure to get the winsock error.
			var bytes, flags uint32
			err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags)
		}
	case <-timeout:
		cancelIoEx(f.handle, &c.o)
		r = <-c.ch
		err = r.err
		if err == syscall.ERROR_OPERATION_ABORTED {
			err = ErrTimeout
		}
	}

	// runtime.KeepAlive is needed, as c is passed via native
	// code to ioCompletionProcessor, c must remain alive
	// until the channel read is complete.
	runtime.KeepAlive(c)
	return int(r.bytes), err
}
1257672
func (tw *timeoutWriter) Write(p []byte) (int, error) {
	if tw.err != nil {
		return 0, tw.err
	}

	var n int
	tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout))
	n, tw.err = tw.conn.Write(p)
	tw.conn.SetWriteDeadline(time.Time{})
	return n, tw.err
}
187905
func (c *Connection) sendChunk(deadline time.Time, chunk chunk) error {
	c.writeMutex.Lock()
	defer c.writeMutex.Unlock()

	c.conn.SetWriteDeadline(deadline)
	var err error
	switch c.version {
	case Version1_0:
		_, err = chunk.WriteToVST1_0(c.conn)
	case Version1_1:
		_, err = chunk.WriteToVST1_1(c.conn)
	default:
		err = driver.WithStack(fmt.Errorf("Unknown protocol version %d", int(c.version)))
	}
	c.updateLastActivity()
	if err != nil {
		return driver.WithStack(err)
	}
	return nil
}
389271
func (c *Conn) Write(p []byte) (int, error) {
	c.conn.SetWriteDeadline(time.Now().Add(c.config.WriteTimeout))
	return c.w.Write(p)
}
161668
func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
	deadline := c.writeCancel()

	// Check if deadline has already expired.
	select {
	case <-deadline:
		return 0, c.newRemoteOpError("write", addr, &timeoutError{})
	default:
	}

	// If we're being called by Write, there is no addr
	wopts := tcpip.WriteOptions{}
	if addr != nil {
		ua := addr.(*net.UDPAddr)
		wopts.To = &tcpip.FullAddress{Addr: tcpip.Address(ua.IP), Port: uint16(ua.Port)}
	}

	v := buffer.NewView(len(b))
	copy(v, b)

	n, resCh, err := c.ep.Write(tcpip.SlicePayload(v), wopts)
	if resCh != nil {
		select {
		case <-deadline:
			return int(n), c.newRemoteOpError("write", addr, &timeoutError{})
		case <-resCh:
		}

		n, _, err = c.ep.Write(tcpip.SlicePayload(v), wopts)
	}

	if err == tcpip.ErrWouldBlock {
		// Create wait queue entry that notifies a channel.
		waitEntry, notifyCh := waiter.NewChannelEntry(nil)
		c.wq.EventRegister(&waitEntry, waiter.EventOut)
		defer c.wq.EventUnregister(&waitEntry)
		for {
			select {
			case <-deadline:
				return int(n), c.newRemoteOpError("write", addr, &timeoutError{})
			case <-notifyCh:
			}

			n, _, err = c.ep.Write(tcpip.SlicePayload(v), wopts)
			if err != tcpip.ErrWouldBlock {
				break
			}
		}
	}

	if err == nil {
		return int(n), nil
	}

	return int(n), c.newRemoteOpError("write", addr, errors.New(err.String()))
}
521325
func (h *pubsubHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	handler := func(socket *websocket.Conn) {
		logger.Debugf("start of *pubsubHandler.ServeHTTP")
		defer socket.Close()

		// If we get to here, no more errors to report, so we report a nil
		// error.  This way the first line of the socket is always a json
		// formatted simple error.
		h.sendError(socket, req, nil)

		// Here we configure the ping/pong handling for the websocket so
		// the server can notice when the client goes away.
		// See the long note in logsink.go for the rationale.
		socket.SetReadDeadline(time.Now().Add(websocket.PongDelay))
		socket.SetPongHandler(func(string) error {
			socket.SetReadDeadline(time.Now().Add(websocket.PongDelay))
			return nil
		})
		ticker := time.NewTicker(websocket.PingPeriod)
		defer ticker.Stop()

		messageCh := h.receiveMessages(socket)
		for {
			select {
			case <-h.ctxt.stop():
				return
			case <-ticker.C:
				deadline := time.Now().Add(websocket.WriteWait)
				if err := socket.WriteControl(gorillaws.PingMessage, []byte{}, deadline); err != nil {
					// This error is expected if the other end goes away. By
					// returning we close the socket through the defer call.
					logger.Debugf("failed to write ping: %s", err)
					return
				}
			case m := <-messageCh:
				logger.Tracef("topic: %q, data: %v", m.Topic, m.Data)
				_, err := h.hub.Publish(m.Topic, m.Data)
				if err != nil {
					logger.Errorf("publish failed: %v", err)
				}
			}
		}
	}
	websocket.Serve(w, req, handler)
}
1196322
func (c *Channel) Write(data string) {
	// Prepend the socket command and send the channel name and data.
	c.s.write(cmdChannelData + utils.MarshalValues(c.name, data))
}