Load data from a given socket, this is a blocking method thus only return when the socket
    connection has been closed.
483251
def _load_from_socket(port, auth_secret):
    
    (sockfile, sock) = local_connect_and_auth(port, auth_secret)
    # The barrier() call may block forever, so no timeout
    sock.settimeout(None)
    # Make a barrier() function call.
    write_int(BARRIER_FUNCTION, sockfile)
    sockfile.flush()

    # Collect result.
    res = UTF8Deserializer().loads(sockfile)

    # Release resources.
    sockfile.close()
    sock.close()

    return res
476669
def run(self):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(self._addr)
        sock.settimeout(self._timeout)
        with closing(sock):
            while not self._shutdown.is_set():
                try:
                    data, addr = sock.recvfrom(self._buffer_size)
                except socket.timeout:
                    continue

                header, rest = parse_packet(data)
                if header.packet_type in _PAYLOADS:
                    payload = parse_payload(rest,
                                            *_PAYLOADS[header.packet_type])
                    self._callbacks.put(header.packet_type,
                                        header, payload, None, addr)
                else:
                    self._callbacks.put(EVENT_UNKNOWN,
                                        header, None, rest, addr)
631486
private void socketClosedHandler() {
        // If the book-keeping has already been completed earlier, then
        // we should just bail.
        if (getReadyState() == ReadyState.CLOSED) {
            return;
        }
        
        // TODO: Determine whether channels need to be cleaned up
        if (this.channels.size() != 0) {
            // Iterate over the channels and close them.
            for (int i = 1; i <= this.channels.size(); i++) { // 1-based
                AmqpChannel channel = this.channels.get(i);
                AmqpFrame   f = new AmqpFrame();
                
                // Close the channel and ensure that the CLOSE event is
                // fired on the registered ChannelListener objects.
                f.setMethodName("closeChannel");
                f.setChannelId((short) i);
                channel.channelClosedHandler(this, "", f, "closeChannel");
            }
        }
        
        // Mark the readyState as CLOSED.
        readyState = ReadyState.CLOSED;

        // Fire the CLOSE event on the ConnectionListener(s) registered on
        // the AmqpClient object.
        fireOnClosed(new ConnectionEvent(this, Kind.CLOSE));
    }
1204988
private void scheduleReconnection() {

        if (runnable != null) {
            handler.removeCallbacks(runnable);
        }

        runnable = () -> {
            if (shouldReconnect() && (socket == null || !socket.isOpen()) && retryStrategy.retry() && !isNetworkUnavailable) {
                log.d("Reconnecting socket");
                connect();
            }
        };
        long delay = retryStrategy.getDelay();
        handler.postDelayed(runnable, delay);
        log.d("Socket reconnection in " + delay / 1000 + " seconds.");
    }
909381
def on_close(socket, *data, &block)
      raise UnknownSocket.new(socket) unless @sockets.has_key?(socket)
      raise ArgumentError.new('Block must be supplied') unless block_given?
      raise ArgumentError.new('Block must allow at least one argument') if block.arity == 0
      if(block.arity > 0 && block.arity != (data.size + 1))
        raise ArgumentError.new('Invalid number of arguments for block')
      end
      @sockets[socket][:closed] ||= []
      @sockets[socket][:closed] << [data, block]
    end
622962
def closed(self, code, reason=None):
        """"""
        self.emit('socket_closed', code, reason)
        self._recover_network_failure()
768131
def fill_inbuffer(self):
		
		if not self.connection:
			raise OmapiError("not connected")
		try:
			data = self.connection.recv(2048)
		except socket.error:
			self.close()
			raise
		if not data:
			self.close()
			raise OmapiError("connection closed")
		try:
			self.protocol.data_received(data)
		except OmapiSizeLimitError:
			self.close()
			raise
855667
def write(self, data):
		
		try:
			self.connection.sendall(data)
		except socket.error:
			self.close()
			raise
992853
def receive(self, sock):
    """"""
    msg = None
    data = b''
    recv_done = False
    recv_len = -1
    while not recv_done:
      buf = sock.recv(BUFSIZE)
      if buf is None or len(buf) == 0:
        raise Exception("socket closed")
      if recv_len == -1:
        recv_len = struct.unpack('>I', buf[:4])[0]
        data += buf[4:]
        recv_len -= len(data)
      else:
        data += buf
        recv_len -= len(buf)
      recv_done = (recv_len == 0)

    msg = pickle.loads(data)
    return msg
93017
def _tcp_socket(self):
        
        sock = iostream.IOStream(socket.socket(
                    socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP))
        sock.connect(self._address, self._tcp_on_connected)
        sock.set_close_callback(self._tcp_on_closed)
        return sock
644872
private Socket nextSocket() {
    Socket result;
    synchronized (lock) {
      result = nextSocket;
      while (!done && result == null) {
        try {
          lock.wait();
        } catch (InterruptedException e) {
          done = true;
        }
        result = nextSocket;
      }
      nextSocket = null;
    }

    if (result != null) {
      // Java InputStream API is blocking by default with no reliable way to stop pending
      // read() call. Setting the timeout to underlying socket will make socket's underlying
      // read() calls throw SocketTimeoutException which unblocks read(). The exception must
      // be properly handled by calling code.
      try {
        // TODO(buck_team): this does not work with current NGUnixDomainSocket
        // implementation
        result.setSoTimeout(this.heartbeatTimeoutMillis);
      } catch (SocketException e) {
        // this exception might be thrown if socket is already closed
        // so we just return null
        return null;
      }
    }

    return result;
  }
705033
def receive(self, timeout=None):
        """"""
        log.debug('Receiving')
        if not self._socket:
            log.warn('No connection')
            return
        try:
            if timeout:
                rv = self._socket.poll(timeout)
                if not rv:
                    log.info('Connection timeouted')
                    return 'Quit'

            data = self._socket.recv_bytes()
        except Exception:
            log.error('Connection lost')
            return 'Quit'
        log.debug('Got %s' % data)
        return data.decode('utf-8')
119901
def receive(new_data)
      return if @state == :closed
      return if new_data.empty?
      @buffer << new_data
      consume_buffer
    rescue RemoteConnectionError => e
      callback(:connection_error, e)
      goaway(e.http2_error_type)
      close
    end
73361
public void run() {

		try {
			while (true) {
				//server thread blocks until a client connects
				Socket socket = server.accept();

				System.out.println(new LogEntry("client (" + socket.getInetAddress().getHostAddress() + ") attempts to connect..."));
				Connection c = establishConnection(socket);
				updateConnectedClients(c);
			}
		} catch (IOException ioe) {
			System.out.println(new LogEntry("server forced to stop with message " + ioe.getClass().getName() + ' ' + ioe.getMessage()));
		} catch (Throwable t) {
			System.out.println(new LogEntry(Level.CRITICAL, "server forced to stop with message " + t.getClass().getName() + ' ' + t.getMessage(), t));
		}
	}
626431
def do_open(self, http_class, req, **http_conn_args):
        
        host = req.host
        if not host:
            raise URLError('no host given')

        # will parse host:port
        h = http_class(host, timeout=req.timeout, **http_conn_args)

        headers = dict(req.unredirected_hdrs)
        headers.update(dict((k, v) for k, v in req.headers.items()
                            if k not in headers))

        # TODO(jhylton): Should this be redesigned to handle
        # persistent connections?

        # We want to make an HTTP/1.1 request, but the addinfourl
        # class isn't prepared to deal with a persistent connection.
        # It will try to read all remaining data from the socket,
        # which will block while the server waits for the next request.
        # So make sure the connection gets closed after the (only)
        # request.
        headers["Connection"] = "close"
        headers = dict((name.title(), val) for name, val in headers.items())

        if req._tunnel_host:
            tunnel_headers = {}
            proxy_auth_hdr = "Proxy-Authorization"
            if proxy_auth_hdr in headers:
                tunnel_headers[proxy_auth_hdr] = headers[proxy_auth_hdr]
                # Proxy-Authorization should not be sent to origin
                # server.
                del headers[proxy_auth_hdr]
            h.set_tunnel(req._tunnel_host, headers=tunnel_headers)

        try:
            h.request(req.get_method(), req.selector, req.data, headers)
        except socket.error as err: # timeout error
            h.close()
            raise URLError(err)
        else:
            r = h.getresponse()
            # If the server does not send us a 'Connection: close' header,
            # HTTPConnection assumes the socket should be left open. Manually
            # mark the socket to be closed when this response object goes away.
            if h.sock:
                h.sock.close()
                h.sock = None


        r.url = req.get_full_url()
        # This line replaces the .msg attribute of the HTTPResponse
        # with .headers, because urllib clients expect the response to
        # have the reason in .msg.  It would be good to mark this
        # attribute is deprecated and get then to use info() or
        # .headers.
        r.msg = r.reason
        return r
1059342
def _on_close(self, socket):
        
        self.logger.debug('Connection closed.')

        for subscription in self.subscriptions.values():
            if subscription.state == 'subscribed':
                subscription.state = 'connection_pending'
954311
def _receive(self):
        
        data_in = EMPTY_BUFFER
        try:
            data_in = self._read_from_socket()
        except socket.timeout:
            pass
        except (IOError, OSError) as why:
            if why.args[0] not in (EWOULDBLOCK, EAGAIN):
                self._exceptions.append(AMQPConnectionError(why))
                self._running.clear()
        return data_in