Checks for any network events on our set of sockets and passes those events down to their
associated {@link NetEventHandler}s for processing.
491292
protected void processIncomingEvents (long iterStamp)
    {
        // process those events
        long bytesIn = 0, msgsIn = 0, eventCount = 0;
        for (SelectionKey selkey : _selectorSelector) {
            eventCount++;
            NetEventHandler handler = null;
            try {
                handler = _handlers.get(selkey);
                if (handler == null) {
                    log.warning("Received network event for unknown handler",
                                "key", selkey, "ops", selkey.readyOps());
                    // request that this key be removed from our selection set, which normally
                    // happens automatically but for some reason didn't
                    selkey.cancel();
                    continue;
                }

//                 log.info("Got event", "selkey", selkey, "handler", handler);

                int got = handler.handleEvent(iterStamp);
                if (got != 0) {
                    bytesIn += got;
                    // we know that the handlers only report having read bytes when they have a
                    // whole message, so we can count thusly
                    msgsIn++;
                }

            } catch (Exception e) {
                log.warning("Error processing network data: " + handler + ".", e);

                // if you freak out here, you go straight in the can
                if (handler != null && handler instanceof Connection) {
                    closeConnection((Connection)handler);
                }
            }
        }

        synchronized (this) {
            // update our stats
            _stats.eventCount += eventCount;
            _stats.bytesIn += bytesIn;
            _stats.msgsIn += msgsIn;
        }
    }
80804
function() {
      if (node.debug) {
        node.log('STARTING event listener');
      }

      var net = require('net');
      var dgram = require('dgram');
      node.inputSocket = dgram.createSocket({type:'udp4', reuseAddr: true});

      node.inputSocket.on('notify', function (event) {
        if (node.debug) {
          node.log('Got a notification.', event)
        }
      });

      node.inputSocket.on('message', function (msg, rinfo) {
        //node.log("[" + rinfo.address + "] --> " + msg.toString());

        if (rinfo.address == node.address) {
          if (node.debug) {
            node.log("UPnP Event from [" + rinfo.address + "] --> " );//+ msg.toString());
          }

          // Split to header and body
          msg = msg.toString().split('\r\n\r\n');
          var header = msg[0];
          var body = msg[1];

          // Ignore UPNP search requests
          var method = header.split('\r\n').shift().split(' ').shift().trim();
          if (method == 'M-SEARCH'){
            return;
          }

          // Parse rest of header
          var arr = header.match(/[^\r\n]+/g);
          var headerInfo = {};
          for (var i = 1; i < arr.length; ++i){
            var tem = arr[i].split(/:(.+)?/);
            if (typeof(tem[1]) == 'string'){ tem[1] = tem[1].trim(); }
            headerInfo[tem[0].toLowerCase()] = tem[1];
          };
          //node.log("METHOD: " + method);
          //node.log("BODY: " + body);
          //node.log("NTS: " + headerInfo['nts']);

          // NOTIFY messages tell us about the properties that changed
          if (method == 'NOTIFY' && headerInfo['nts'] == 'yamaha:propchange') {

            var parseString = require('xml2js').parseString;
            parseString(body, function (err, result) {
              if (err) {
                node.error('Failed to parse the event with error: ' + err);
                return;
              }

              // Check the received object
              var zoneName = undefined;
              if (result.hasOwnProperty('YAMAHA_AV')) {
                if (result.YAMAHA_AV.hasOwnProperty('Main_Zone')) {
                  zoneName = 'Main_Zone';
                } else if (result.YAMAHA_AV.hasOwnProperty('Zone_2')) {
                  zoneName = 'Zone_2';
                } else if (result.YAMAHA_AV.hasOwnProperty('Zone_3')) {
                  zoneName = 'Zone_3';
                } else if (result.YAMAHA_AV.hasOwnProperty('Zone_4')) {
                  zoneName = 'Zone_4';
                }
              }
              if (zoneName === undefined
                || result.YAMAHA_AV[zoneName] === undefined
                || result.YAMAHA_AV[zoneName][0] === undefined) {
                if (node.debug) {
                  node.warn('Unknown event message format: ' + JSON.stringify(result));
                }
                return;
              }

              for (var i in result.YAMAHA_AV[zoneName][0].Property) {
                var prop = result.YAMAHA_AV[zoneName][0].Property[i];
                if (node.debug) {
                  node.log('Property-Change: ' + prop);
                }

                // Event Notification only notifies that there is a change in each item.
                // It is necessary to issue the GET command to obtain the content of the item with the change.
                if (prop == 'Power') {

                  // Get current power state and publish to all subscriber.
                  node.sendGetCommand(zoneName + '.Power_Control.Power').then(function(value) {
                    for (var s in node.subscriptions) {
                      node.subscriptions[s].handler(zoneName + '.Power_Control.Power', value);
                    }
                  }).catch(function(error) {
                    node.error('Failed to request data from AVR with error: ' + error);
                  });

                } else if (prop == 'Input') {

                  // Get current input selection and publish to all subscriber.
                  node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) {
                    for (var s in node.subscriptions) {
                      node.subscriptions[s].handler(zoneName + '.Input.Input_Sel', value);
                    }
                  }).catch(function(error) {
                    node.error('Failed to request data from AVR with error: ' + error);
                  });

                } else if (prop == 'Volume') {

                  // We don't know from the event itself if volume changed or mute/unmute was pressed.
                  // Therefore we read both states.
                  node.sendGetCommand(zoneName + '.Volume.Lvl').then(function(value) {
                    for (var s in node.subscriptions) {
                      node.subscriptions[s].handler(zoneName + '.Volume.Lvl', value);
                    }
                  }).catch(function(error) {
                    node.error('Failed to request data from AVR with error: ' + error);
                  });
                  node.sendGetCommand(zoneName + '.Volume.Mute').then(function(value) {
                    for (var s in node.subscriptions) {
                      node.subscriptions[s].handler(zoneName + '.Volume.Mute', value);
                    }
                  }).catch(function(error) {
                    node.error('Failed to request data from AVR with error: ' + error);
                  });

                } else if (prop == 'Play_Info') {

                  // When getting the Play_Info event we need to check the current input mode and then read
                  // the corresponding item that holds info about current mode.
                  node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) {

                    var validInputs = {
                      'TUNER': 'Tuner', 'Napster': 'Napster', 'Spotify': 'Spotify', 'JUKE': 'JUKE', 'SERVER': 'SERVER',
                      'NET RADIO': 'NET_RADIO', 'USB': 'USB', 'iPod_USB': 'iPod_USB', 'AirPlay': 'AirPlay'
                    };

                    if (validInputs.hasOwnProperty(value)) {
                      node.sendGetCommand(validInputs[value] + '.Play_Info').then(function(value2) {
                        for (var s in node.subscriptions) {
                          node.subscriptions[s].handler(value + '.Play_Info', value2);
                        }
                      }).catch(function(error) {
                        node.error('Received event Play_Info but failed to read play info of current input selection: ' + error);
                      });
                    } else {
                      if (node.debug) {
                        node.log('Received event Play_Info but do not know or support current input selection ' + value);
                      }
                    }
                  }).catch(function(error) {
                    node.error('Received event Play_Info but failed to read current input selection: ' + error);
                  });

                } else if (prop == 'List_Info') {

                  // When getting the List_info event we need to check the current input mode and then read
                  // the corresponding item that holds info about current mode.
                  node.sendGetCommand(zoneName + '.Input.Input_Sel').then(function(value) {

                    var validInputs = {
                      'Napster': 'Napster', 'JUKE': 'JUKE', 'SERVER': 'SERVER',
                      'NET RADIO': 'NET_RADIO', 'USB': 'USB', 'iPod_USB': 'iPod_USB'
                    };

                    if (validInputs.hasOwnProperty(value)) {
                      node.sendGetCommand(validInputs[value] + '.List_Info').then(function(value2) {
                        for (var s in node.subscriptions) {
                          node.subscriptions[s].handler(value + '.List_Info', value2);
                        }
                      }).catch(function(error) {
                        node.error('Received event List_Info but failed to read play info of current input selection: ' + error);
                      });
                    } else {
                      if (node.debug) {
                        node.log('Received event List_Info but do not know or support current input selection ' + value);
                      }
                    }
                  }).catch(function(error) {
                    node.error('Received event List_Info but failed to read current input selection: ' + error);
                  });

                } else {

                  // The event is not known. Maybe the AVR is too new.
                  if (node.debug) {
                    node.log('Received unsupported Property-Change via multicast: ' + prop);
                  }
                  return;

                }
              }
            });
          }
        }
      });

      node.inputSocket.on('listening', function () {
        try {
          var address = node.inputSocket.address();
          node.log('UDP client listening on ' + address.address + ":" + address.port);
          node.inputSocket.setBroadcast(true)
          node.inputSocket.setMulticastTTL(5);
          node.inputSocket.addMembership('239.255.255.250');
          //node.inputSocket.addMembership('239.255.255.250', '192.168.0.101');
          //node.inputSocket.addMembership('239.255.255.250', '127.0.0.1');

          /*
          var message = new Buffer(
            "M-SEARCH * HTTP/1.1\r\n" +
            "HOST: 239.255.255.250:1900\r\n" +
            "MAN: \"ssdp:discover\"\r\n" +
            "ST: ssdp:all\r\n" + // Essential, used by the client to specify what they want to discover, eg 'ST:ge:fridge'
            "MX: 3\r\n" + // 1 second to respond (but they all respond immediately?)
            "\r\n");
          */

            //node.inputSocket.send(message, 0, message.length, 1900, "239.255.255.250");
          } catch (err) {
            node.warn('Cannot bind address for UPNP event listener. Port probably already in use. Error: ' + err);
          }
        });

      try {
        node.inputSocket.bind(1900);
      }
      catch (err) {
        node.warn('Cannot bind address for UPNP event listener. Port probably already in use. Error: ' + err);
      }
    }
555603
public void setEvents(java.util.Collection<DeviceEvent> events) {
        if (events == null) {
            this.events = null;
            return;
        }

        this.events = new java.util.ArrayList<DeviceEvent>(events);
    }
1264873
@SuppressWarnings("PMD.UseVarargs")
    /* default */ void dispatch(EventPipeline pipeline,
            EventBase<?> event, Channel[] channels) {
        HandlerList handlers = getEventHandlers(event, channels);
        handlers.process(pipeline, event);
    }
870751
private void initEventTypes(IoEventType... eventTypes) {
        if ((eventTypes == null) || (eventTypes.length == 0)) {
            eventTypes = DEFAULT_EVENT_SET;
        }

        // Copy the list of handled events in the event set
        this.eventTypes = EnumSet.of(eventTypes[0], eventTypes);
        
        // Check that we don't have the SESSION_CREATED event in the set
        if (this.eventTypes.contains( IoEventType.SESSION_CREATED )) {
            this.eventTypes = null;
            throw new IllegalArgumentException(IoEventType.SESSION_CREATED
                + " is not allowed.");
        }
    }
884636
public boolean hasEvents(final EventType _eventtype)
    {
        if (!this.eventChecked) {
            this.eventChecked = true;
            try {
                EventDefinition.addEvents(this);
            } catch (final EFapsException e) {
                AbstractAdminObject.LOG.error("Could not read events for Name:; {}', UUID: {}",  this.name, this.uuid);
            }
        }
        return this.events.get(_eventtype) != null;
    }
1164990
async def _next_event(self):
        
        while True:
            for event in self._connection.events():
                if isinstance(event, Message):
                    # check if we need to buffer
                    if event.message_finished:
                        return self._wrap_data(self._gather_buffers(event))
                    self._buffer(event)
                    break  # exit for loop
                else:
                    return event

            data = await self._sock.receive_some(4096)
            if not data:
                return CloseConnection(code=500, reason="Socket closed")
            self._connection.receive_data(data)
280821
private synchronized void closeAllAcceptedSockets() {
    for (int x = 0; x < socketList.size(); x++) {
      try {
        ((Socket) socketList.get(x)).close();
      } catch (Exception e) {
        // ignore for now
      }
    }

    // clear member variables
    socketMap.clear();
    socketList.clear();
  }
625796
public void sendEventsFromQueue() {
        if (null == queue || stopSending) {
            return;
        }
        LOG.fine("Scheduler called for sending events");

        int packageSize = getEventsPerMessageCall();

        while (!queue.isEmpty()) {
            final List<Event> list = new ArrayList<Event>();
            int i = 0;
            while (i < packageSize && !queue.isEmpty()) {
                Event event = queue.remove();
                if (event != null && !filter(event)) {
                    list.add(event);
                    i++;
                }
            }
            if (list.size() > 0) {
                executor.execute(new Runnable() {
                    public void run() {
                        try {
                            sendEvents(list);
                        } catch (MonitoringException e) {
                            e.logException(Level.SEVERE);
                        }
                    }
                });

            }
        }

    }
553235
protected function ensureEvents()
	{
		if ($this->_events === null) {
			$this->_events = [];
			if (method_exists($this, 'events')) {
			    if ($events = $this->events()) foreach ($events as $name => $handler) {
					$this->on($name, $handler);
				}
			}
		}
	}
963761
public void handleDebugEvents(DebugEvent[] events)
	{
		for (int i = 0; i < events.length; i++)
		{
			DebugEvent event = events[i];
			if (event.getSource().equals(getProcess()))
			{

				if (event.getKind() == DebugEvent.TERMINATE)
				{
					closeStreams();
					DebugPlugin.getDefault().removeDebugEventListener(this);
				}

				resetName();
			}
		}
	}
107177
def _handle_events(self, fd: int, events: int) -> None:
        
        action = 0
        if events & ioloop.IOLoop.READ:
            action |= pycurl.CSELECT_IN
        if events & ioloop.IOLoop.WRITE:
            action |= pycurl.CSELECT_OUT
        while True:
            try:
                ret, num_handles = self._multi.socket_action(fd, action)
            except pycurl.error as e:
                ret = e.args[0]
            if ret != pycurl.E_CALL_MULTI_PERFORM:
                break
        self._finish_pending_requests()
1166782
protected boolean handleEvent(AbstractEvent event) throws IOException {
		final Class<?> eventType = event.getClass();

		try {
			// ------------------------------------------------------------
			// Runtime events
			// ------------------------------------------------------------

			// This event is also checked at the (single) input gate to release the respective
			// channel, at which it was received.
			if (eventType == EndOfPartitionEvent.class) {
				return true;
			}
			else if (eventType == EndOfSuperstepEvent.class) {
				return incrementEndOfSuperstepEventAndCheck();
			}

			// ------------------------------------------------------------
			// Task events (user)
			// ------------------------------------------------------------
			else if (event instanceof TaskEvent) {
				taskEventHandler.publish((TaskEvent) event);

				return false;
			}
			else {
				throw new IllegalStateException("Received unexpected event of type " + eventType + " at reader.");
			}
		}
		catch (Throwable t) {
			throw new IOException("Error while handling event of type " + eventType + ": " + t.getMessage(), t);
		}
	}
678310
private void signalConnected() {
        if (alternate != null) {
            LOGGER.info("Connected to Node {} ({})",
                system(hostname.nameAndAddress()), system(alternate.nameAndAddress()));
        } else {
            LOGGER.info("Connected to Node {}", system(hostname.nameAndAddress()));
        }
        if (eventBus != null && eventBus.hasSubscribers()) {
            eventBus.publish(new NodeConnectedEvent(hostname));
        }
    }
1297554
def events(self):
        
        if not self.__events:
            self.__events = Events(self.__connection)
        return self.__events
548032
@Deprecated
  @SuppressWarnings({"deprecation"})
  public TimedEvents<io.opencensus.trace.NetworkEvent> getNetworkEvents() {
    TimedEvents<MessageEvent> timedEvents = getMessageEvents();
    List<TimedEvent<io.opencensus.trace.NetworkEvent>> networkEventsList =
        new ArrayList<TimedEvent<io.opencensus.trace.NetworkEvent>>();
    for (TimedEvent<MessageEvent> timedEvent : timedEvents.getEvents()) {
      networkEventsList.add(
          TimedEvent.<io.opencensus.trace.NetworkEvent>create(
              timedEvent.getTimestamp(),
              BaseMessageEventUtils.asNetworkEvent(timedEvent.getEvent())));
    }
    return TimedEvents.<io.opencensus.trace.NetworkEvent>create(
        networkEventsList, timedEvents.getDroppedEventsCount());
  }
229304
protected function __bindEvents()
    {
        $server = $this->swoolePort ?? $this->swooleServer;

        $server->on('packet', function(\swoole_server $server, $data, $clientInfo){
            try{
                $this->trigger('packet', [
                    'server'        => $this,
                    'data'          => $data,
                    'clientInfo'    => $clientInfo,
                ], $this, PacketEventParam::class);
            }
            catch(\Throwable $ex)
            {
                App::getBean('ErrorLog')->onException($ex);
            }
        });
        
    }