1) Inject the online customer collection factory in your constructor
public function __construct(
Magento\Customer\Model\ResourceModel\Online\Grid\CollectionFactory $onlineCustomerCollectionFactory
) {
$this->onlineCustomerCollectionFactory = $this->onlineCustomerCollectionFactory;
}
2) now create a collection object and apply appropriate filters and load it in your function. Optimize the logic as per your need. I am providing a general code.
public function getOnlineCustomers() {
$onlineCustomersCollection = $this->onlineCustomerCollectionFactory->create();
/**
* this will return all the customers that are online including
* registered and non-registered. So apply filters as per your
* your requirement using addFieldToFilter() function on collection
*/
$onlineCustomers = $onlineCustomerCollection->load()->getItems();
return $onlineCustomers;
}