Starts the listen loop and executes the receieve_datagram method
        whenever a packet is receieved.

        Args:
          None

        Returns:
          None
344408
def listen_loop(self):
        

        while self.listening:
            try:
                data, address = self.sock.recvfrom(self.bufsize)
                self.receive_datagram(data, address)
                if self.stats_enabled:
                    self.stats['bytes_recieved'] += len(data)
            except socket.error as error:
                if error.errno == errno.WSAECONNRESET:
                    logger.info("connection reset")
                else:
                    raise

        logger.info("Shutting down the listener...")
990517
async def listen(self, port, interface='0.0.0.0'):
        
        loop = asyncio.get_event_loop()
        listen = loop.create_datagram_endpoint(self._create_protocol,
                                               local_addr=(interface, port))
        log.info("Node %i listening on %s:%i",
                 self.node.long_id, interface, port)
        self.transport, self.protocol = await listen
        # finally, schedule refreshing table
        self.refresh_table()
1291200
def _async_recv(self):
        """"""

        logging.info("Receive loop started")
        recbuffer = b""

        while not self._stop_event.is_set():
            time.sleep(0.01)
            try:
                recbuffer = recbuffer + self._socket.recv(1024)
                data = recbuffer.split(b'\r\n')
                recbuffer = data.pop()
                if data:
                    for line in data:
                        self._process_data(line.decode(encoding='UTF-8', errors='ignore'))
            except BlockingIOError as e:
                pass
        logging.info("Receive loop stopped")
578361
def _recv(self):
        

        # Outer loop: receive some data
        while True:
            # Wait until we can go
            self._recv_lock.release()
            gevent.sleep()  # Yield to another thread
            self._recv_lock.acquire()

            recv_buf = self._sock.recv(self.recv_bufsize)

            # If it's empty, the peer closed the other end
            if not recv_buf:
                # Manually kill the send thread; do this manually
                # instead of calling close() because close() will kill
                # us, and since close() would be running in our thread
                # context, it would never get around to killing the
                # send thread
                if self._send_thread:
                    self._send_thread.kill()
                    self._send_thread = None

                # Manually close the socket
                self._sock.close()
                self._sock = None

                # Make sure the manager knows we're closed
                super(TCPTendril, self).close()

                # Notify the application
                self.closed()

                # As our last step, commit seppuku; this will keep
                # _thread_error() from notifying the application of an
                # erroneous exit from the receive thread
                raise gevent.GreenletExit()

            # Process the received data
            self._recv_frameify(recv_buf)
1066063
def _receiving(self):
        
        while self._is_running:
            try:
                rlist, wlist, xlist = select.select(
                    self._listening, [], [],
                    self._select_timeout
                )
            except:
                self.exception("Failed to select socket")
                continue
            for sock in rlist:
                try:
                    self._get_packet(sock)
                except:
                    self.exception("Failed to receive packet")
76586
def _start_loop(self, websocket, event_handler):
		
		log.debug('Starting websocket loop')
		while True:
			try:
				yield from asyncio.wait_for(
					self._wait_for_message(websocket, event_handler),
					timeout=self.options['timeout']
				)
			except asyncio.TimeoutError:
				yield from websocket.pong()
				log.debug("Sending heartbeat...")
				continue
507666
function listen(next) {

        listenSocket = dgram.createSocket({ type: 'udp4', reuseAddr: true });

        listenSocket.on('message', function(payload, rinfo) {
            var message = parseMessage(payload, rinfo);
            if (message) {
                if (message.id != id) {
                    if (message.status == "ONE") {
                        updateNodeList(message);
                    } else if (message.name != listenNameIdentifier && message.status == "NAMETAKEN") {
                        stop(function() {
                            //throw new Error('name already taken "' + name + '"');
                            self.emit("error", {cause: "Name already taken"});
                        });
                    }
                } else {
                    //self.emit('error', id + " already exists in network");
                    throw new Error(id + ' already exits in network');
                    stop();
                }
            }
        });

        listenSocket.bind(function(err) {
            var info = listenSocket.address();
            self.port = info.port;
            next(err);
        });

    }
712430
def start_receive(self, fd, data=None):
        
        self._rfds[fd] = (data or fd, self._generation)
        self._update(fd)
591268
def _on_recv_complete(self, handle, addr, flags, data, error):
        """"""
        assert handle is self._handle
        if error:
            self._log.warning('pyuv error {} in recv callback', error)
            self._protocol.error_received(TransportError.from_errno(error))
        elif flags:
            assert flags & pyuv.UV_UDP_PARTIAL
            self._log.warning('ignoring partial datagram')
        elif data:
            self._protocol.datagram_received(data, addr)
239740
def listen(self, timeout=10):
        
        self._socket.settimeout(float(timeout))
        while not self.stopped.isSet():
            try:
                data, client_address = self._socket.recvfrom(4096)
                if len(client_address) > 2:
                    client_address = (client_address[0], client_address[1])
            except socket.timeout:
                continue
            except Exception as e:
                if self._cb_ignore_listen_exception is not None and isinstance(self._cb_ignore_listen_exception, collections.Callable):
                    if self._cb_ignore_listen_exception(e, self):
                        continue
                raise
            try:
                serializer = Serializer()
                message = serializer.deserialize(data, client_address)
                if isinstance(message, int):
                    logger.error("receive_datagram - BAD REQUEST")

                    rst = Message()
                    rst.destination = client_address
                    rst.type = defines.Types["RST"]
                    rst.code = message
                    rst.mid = self._messageLayer.fetch_mid()
                    self.send_datagram(rst)
                    continue

                logger.debug("receive_datagram - " + str(message))
                if isinstance(message, Request):
                    transaction = self._messageLayer.receive_request(message)
                    if transaction.request.duplicated and transaction.completed:
                        logger.debug("message duplicated, transaction completed")
                        if transaction.response is not None:
                            self.send_datagram(transaction.response)
                        continue
                    elif transaction.request.duplicated and not transaction.completed:
                        logger.debug("message duplicated, transaction NOT completed")
                        self._send_ack(transaction)
                        continue
                    args = (transaction, )
                    t = threading.Thread(target=self.receive_request, args=args)
                    t.start()
                # self.receive_datagram(data, client_address)
                elif isinstance(message, Response):
                    logger.error("Received response from %s", message.source)

                else:  # is Message
                    transaction = self._messageLayer.receive_empty(message)
                    if transaction is not None:
                        with transaction:
                            self._blockLayer.receive_empty(message, transaction)
                            self._observeLayer.receive_empty(message, transaction)

            except RuntimeError:
                logger.exception("Exception with Executor")
        self._socket.close()
359450
def __receiver_loop(self):
        
        log.info("Starting receiver loop")
        notify_disconnected = True
        try:
            while self.running:
                try:
                    while self.running:
                        frames = self.__read()

                        for frame in frames:
                            f = utils.parse_frame(frame)
                            if f is None:
                                continue
                            if self.__auto_decode:
                                f.body = decode(f.body)
                            self.process_frame(f, frame)
                except exception.ConnectionClosedException:
                    if self.running:
                        #
                        # Clear out any half-received messages after losing connection
                        #
                        self.__recvbuf = b''
                        self.running = False
                        notify_disconnected = True
                    break
                finally:
                    self.cleanup()
        finally:
            with self.__receiver_thread_exit_condition:
                self.__receiver_thread_exited = True
                self.__receiver_thread_exit_condition.notifyAll()
            log.info("Receiver loop ended")
            self.notify('receiver_loop_completed')
            if notify_disconnected:
                self.notify('disconnected')
            with self.__connect_wait_condition:
                self.__connect_wait_condition.notifyAll()
793492
async def on_connect(self, connection):
        ""
        # NOTE: for python3, we can't pass bytestrings as keyword arguments
        # so we need to decode channel/pattern names back to str strings
        # before passing them to [p]subscribe.
        if self.channels:
            channels = {}
            for k, v in iteritems(self.channels):
                if not self.decode_responses:
                    k = k.decode(self.encoding)
                channels[k] = v
            await self.subscribe(**channels)
        if self.patterns:
            patterns = {}
            for k, v in iteritems(self.patterns):
                if not self.decode_responses:
                    k = k.decode(self.encoding)
                patterns[k] = v
            await self.psubscribe(**patterns)
1364357
def send_datagram(self, message):
        
        host, port = message.destination
        logger.debug("send_datagram - " + str(message))
        serializer = Serializer()
        raw_message = serializer.serialize(message)

        try:
            self._socket.sendto(raw_message, (host, port))
        except Exception as e:
            if self._cb_ignore_write_exception is not None and isinstance(self._cb_ignore_write_exception, collections.Callable):
                if not self._cb_ignore_write_exception(e, self):
                    raise

        # if you're explicitly setting that you don't want a response, don't wait for it
        # https://tools.ietf.org/html/rfc7967#section-2.1
        for opt in message.options:
            if opt.number == defines.OptionRegistry.NO_RESPONSE.number:
                if opt.value == 26:
                    return

        if self._receiver_thread is None or not self._receiver_thread.isAlive():
            self._receiver_thread = threading.Thread(target=self.receive_datagram)
            self._receiver_thread.daemon = True
            self._receiver_thread.start()
926609
def run(self):
        
        while True:
            self._logger.debug('Accepting connection')
            conn, addr = self._sock.accept()
            self._talk = SocketTalk(conn, encode=self._encode)

            self._logger.debug('Receiving action')
            action = self._receive()

            if self._on_action:
                self._on_action(action)

            key = None
            if action in ('set', 'get', 'del',):
                self._logger.debug('Receiving key')
                key = self._receive()

            value = None
            if action in ('set',):
                self._logger.debug('Receiving value')
                value = self._receive()

            # Process the request.
            if action == 'stop':
                self._send('ok')

            elif action == 'set':
                self._data[key] = value
                self._send('ok')

            elif action == 'get':
                try:
                    value = self._data[key]
                except:
                    self._logger.debug('Sending "key not found"')
                    self._send('key not found')
                else:
                    self._logger.debug('Sending "ok"')
                    self._send('ok')
                    self._logger.debug('Sending value')
                    self._send(value)

            elif action == 'del':
                try:
                    del self._data[key]
                except:
                    self._logger.debug('Sending "key not found"')
                    self._send('key not found')
                else:
                    self._logger.debug('Sending "ok"')
                    self._send('ok')

            elif action == 'size':
                self._send('ok')
                self._send(str(len(self._data)))

            elif action == 'keys':
                pickled = pickle.dumps(self._data.keys())
                self._send('ok')
                self._send(pickled)

            else:
                self._send('unknown action %s' % action)

            self._logger.debug('Closing')
            try:
                conn.shutdown(socket.SHUT_RDWR)
            except:
                self._logger.error('Failed to shutdown')
            conn.close()

            if action == 'stop':
                break

        self._logger.debug('Stopped')
1336460
def dataReceived(self, data):
        
#        print "receiver dataReceived: <%s>" % data
        
        msg = stomper.unpack_frame(data)
        
        returned = self.sm.react(msg)

#        print "receiver returned <%s>" % returned
        
        if returned:
            self.transport.write(returned)
284840
def start(self):
        
        assert not self._started
        self._listening_stream.on_recv(self._recv_callback)
        self._started = True
1043042
async def _recv_loop(self):
        
        while self._connected:
            try:
                data = await self._recv()
            except asyncio.CancelledError:
                break
            except Exception as e:
                if isinstance(e, (IOError, asyncio.IncompleteReadError)):
                    msg = 'The server closed the connection'
                    self._log.info(msg)
                elif isinstance(e, InvalidChecksumError):
                    msg = 'The server response had an invalid checksum'
                    self._log.info(msg)
                else:
                    msg = 'Unexpected exception in the receive loop'
                    self._log.exception(msg)

                await self.disconnect()

                # Add a sentinel value to unstuck recv
                if self._recv_queue.empty():
                    self._recv_queue.put_nowait(None)

                break

            try:
                await self._recv_queue.put(data)
            except asyncio.CancelledError:
                break